2016-02-05 80 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