首页 > 解决方案 > VBA 编译错误 - 预期 If 或 Select 或 Sub 或 Function 或 End of statement

问题描述

我最近遇到了 VBA 编译错误:“预期:If 或 Select 或 Sub 或 Function 或 Property 或 Type 或 With 或 Enum 或 End of statement”

我所有的 if 语句都已关闭,我没有看到任何其他语法错误。

这是代码:

Option Explicit

Sub whileloop()

Dim intCurrentRow As Integer
Dim intLastRow As Integer
Dim strPrefix As String
Dim strSuffix As String
Dim strOperation As String
Dim snglLaborMinutes As Single



intCurrentRow = 3
intLastRow = Cells(Rows.Count, 0).End(xlUp).Row
strPrefix = Cells(2, 0).Value
strSuffix = Cells(2, 1).Value
strOperation = Cells(2, 4).Value
snglLaborMinutes = Cells(2, 3).Value

While intCurrentRow <= intLastRow
    If strPrefix = Cells(intCurrentRow, 0).Value Then
        If strSuffix = Cells(intCurrentRow, 1).Value Then
            If strOperation = Cells(intCurrentRow, 4).Value Then
                snglLaborMinutes = snglLaborMinutes + Cells(intCurrentRow, 3).Value
                Cells(intCurrentRow - 1, 3).Value = snglLaborMinutes
                Rows(1).EntireRow.Delete
                intLastRow = intLastRow - 1
                intCurrentRow = intCurrentRow - 1
            Else
                strOperation = Cells(intCurrentRow, 4).Value
            End If
        Else
             strSuffix = Cells(intCurrentRow, 1).Value
        End If
    Else
         strPrefix = Cells(intCurrentRow, 0).Value
    End If

intCurrentRow = intCurrentRow + 1

End While


End Sub

标签: excelvbacompiler-errors

解决方案


While 的语法可以在这里查找,但 AFAIK 保留它是为了向后兼容。

你最好使用Do Loop

While intCurrentRow <= intLastRow
  ' .... 

   intCurrentRow = intCurrentRow + 1

Wend

分别

Do While intCurrentRow <= intLastRow
   ' ....

    intCurrentRow = intCurrentRow + 1

Loop

在您的情况下,使用For 循环可能会更好

Dim i as long
For i = intCurrentRow To intLastRow


    ' intCurrentRow = intCurrentRow + 1  not needed any longer

Next i

推荐阅读