2016-02-05 79 views
0

我在VBA很新,所以我敢肯定,我想的東西容易...我得到一個編譯錯誤「循環離不開」做環路誤差在VBA代碼

被調用函數GrabDataFromMinutes我已經自行測試成功了。任何幫助表示讚賞,謝謝!

Public Sub CopyAllData() 

Dim Location As String 
Location = ActiveCell.Address 
Dim CellValue As String 
CellValue = ActiveCell.Value 

Do 
    If IsEmpty(CellValue) = True Then 'If cell is empty skip row' 
     ActiveCell.Offset(rowOffset:=1, ColumnOffset:=-1).Activate 
     Loop 

If Location <> "C350" Then 'run the command unless EOF' 
     Application.Run ("GrabDataFromMinutes") 
     MsgBox "I got here" 
     Location = ActiveCell.Address 
     Loop 

    End If 

Exit Do 

End Sub 
+2

您需要切換結束if和loop。如果在循環內啓動,則不能在循環外部結束循環。也刪除退出做。 –

+0

你只想去一排嗎?現在你的代碼會向下一行,一列過來 – Davesexcel

回答

0

正如Scott正確提到的那樣,您需要將LOOP語句放在相應的位置。 Click Here

您的代碼應該是這樣的

Public Sub CopyAllData() 

Dim Location As String 
Location = ActiveCell.Address 
Dim CellValue As String 
CellValue = ActiveCell.Value 

Do 
    If IsEmpty(CellValue) = True Then 'If cell is empty skip row' 
     ActiveCell.Offset(rowOffset:=1, ColumnOffset:=-1).Activate 

    If Location <> "C350" Then 'run the command unless EOF' 
     Application.Run ("GrabDataFromMinutes") 
     MsgBox "I got here" 
     Location = ActiveCell.Address 

    End If 

    End If 
Loop 

End Sub 
0

這是最終的解決方案,以我自己的問題。其他答案提供的信息有助於解決我的問題。感謝大家!

Public Sub CopyAllData() 
'Declarations' 
Dim CellValue As String 
Dim LastRow As Integer 
Dim CurrentRow As Integer 

Application.Run ("CopyMinuteHeaders") 'Copy Headers and setup sheet' 

'Initialize values' 
CellValue = ActiveCell.Value 
CurrentRow = ActiveCell.Row 
LastRow = ActiveSheet.UsedRange.Rows.Count 
LastRow = LastRow + 1 

Do While LastRow <> CurrentRow 

     If CurrentRow >= LastRow Then 
     Exit Sub 
     End If 

     If CellValue = "" Then 'If cell is empty skip row' 
     Do While CellValue = "" 'Skip multiple rows that are empty' 
      ActiveCell.Offset(rowOffset:=1, ColumnOffset:=0).Activate 
      CellValue = ActiveCell.Value 
      Loop 

     End If 

     If CurrentRow <> LastRow Then 
     Application.Run ("GrabDataFromMinutes") 
     CurrentRow = ActiveCell.Row 
     CellValue = ActiveCell.Value 
     End If 

Loop 


End Sub 
0

我不知道你的GrabDataFromMinutes宏做什麼,我會假設它雖然與活動單元格的交易。通常我會盡量不使用select或activate來提供代碼。如果您要提供GrabDataFromMinutes的代碼,可能會爲您找到更好的解決方案。

與此代碼同時實踐中,它將只選擇列A中的非空白單元格並調用otherMacro

Sub LoopNonBlanks() 
    Dim Lstrw As Long 
    Dim Rng As Range 
    Dim c As Range 

    Lstrw = Cells(Rows.Count, "A").End(xlUp).Row 
    Set Rng = Range("A2:A" & Lstrw).SpecialCells(xlCellTypeConstants, 23) 

    For Each c In Rng.Cells 
     c.Select 
     otherMacro 'calls the otherMacro 
    Next c 
End Sub 
Sub otherMacro() 
    MsgBox "This is the other macro " & ActiveCell.Address & " value is ..." & ActiveCell.Value 
End Sub