【问题标题】:Using "For-Next" inside "If" (Excel, VBA)在“If”中使用“For-Next”(Excel、VBA)
【发布时间】:2016-07-15 12:29:44
【问题描述】:

我正在尝试将多个 "If"s 和一个 "For-Next" 语句组合在一个 "If" 中(代码如下)。不幸的是,我总是收到一条错误消息:“编译错误:没有 If 的其他情况”。你能看看我的代码有没有错误?

Sub Debugging()

Workbooks("Problem.xls").Worksheets(1).Activate

Cash_Rows = 5
Share_Rows = 6

If Cash_Rows <= Share_Rows Then

    Range("A1:A" & Cash_Rows).Select
    With Selection.Interior
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = 0.399975585192419

    Count_Cash = Application.WorksheetFunction.CountIf(Range("A:A"), "L*")

    For Each cell In Range("A1:A" & Cash_Rows)
        If CStr(cell.Value) Like "L*" Then
        Range("A" & cell.Row & ":" & "D" & cell.Row).Interior.Color = 65535
        Dim Index As Integer
        Index = Application.WorksheetFunction.Match(CStr(cell.Value), Range("F2:" & "F" & Share_Rows), 0)
        Range("F" & Index & ":" & "I" & Index).Interior.Color = 65535
        End If
    Next

    If Count_Cash = 0 Then
        MsgBox "You do not have any matching ID+Amount between Cash and Shares booking. It's OK!"
    Else
        MsgBox "You have " & Count_Cash & " matching transactions. Check them!"
    End If

Else

MsgBox "Do not worry. Be happy!"

End If
End Sub

提前感谢您的帮助!

【问题讨论】:

  • 你在.TintAndShade = 0.399975585192419之后缺少End With

标签: excel vba if-statement for-loop


【解决方案1】:

您需要结束with

With Selection.Interior
    .ThemeColor = xlThemeColorAccent6
    .TintAndShade = 0.399975585192419
End With

【讨论】:

  • 只是为了给这个简洁而正确的答案添加一个解释。您可以将IF ... END IF 嵌套在WITH ... END WITH 中(反之亦然),但不允许重叠的语句集。因此,VBA 正在尝试将您的最后一个 ELSE 与您的 IF 匹配在您的 WITH 之后 - 它不能,因此出现错误消息。像大多数编译器/解释器一样,VBA 是愚蠢但合乎逻辑的 - 阅读错误消息并找出真正出错的地方需要经验。
  • 非常感谢大家!很有帮助!
  • 您可以通过单击答案旁边的勾号来接受正确的答案,如果它有助于帮助其他用户解决相同的问题。
猜你喜欢
  • 2019-11-03
  • 1970-01-01
  • 2015-05-15
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
相关资源
最近更新 更多