如何修复VBA中的‘End If无对应块If’编译错误?
解决VBA编译错误:End If找不到对应的块If语句
错误原因
你的代码嵌套结构不匹配:第一个If cStatus Is Nothing Then块内部包含Do While循环,但你把对应这个If的End If写在了Loop语句前面,导致Do While循环未被正确闭合,同时End If找不到对应的起始If语句,触发编译错误。
修正后的代码
Sub YourSubName() ' 替换为你的实际过程名称 Dim cStatus As Range Dim wsDest As Worksheet If cStatus Is Nothing Then Set cStatus = Sheet1.Range("N1:N1000").Find(what:="Done, On-going") ' 先判断是否找到目标单元格,避免后续取值报错 If Not cStatus Is Nothing Then Do While Len(cStatus.Value) > 0 Select Case LCase(cStatus.Value) Case "done": Set wsDest = Sheet4 Case "on-going": Set wsDest = Sheet2 Case Else: Set wsDest = Nothing End Select If Not wsDest Is Nothing Then cStatus.EntireRow.Cut _ Destination:=wsDest.Cells(Rows.Count, "A").End(xlUp).Offset(1) End If ' 取消注释该行,才能遍历下一行,避免死循环 Set cStatus = cStatus.Offset(1, 0) 'next source row Loop End If ' 对应新增的"判断cStatus是否存在"的If块 End If ' 对应最开始的If cStatus Is Nothing Then块 End Sub
额外注意事项
- 原代码中
Find的what参数是"Done, On-going",但后续判断的是单独的"done"和"on-going",如果需求是查找这两种状态的单元格,这个Find逻辑可能不符合预期,建议改为遍历范围或使用FindNext批量查找。 - 原代码中
Set cStatus = cStatus.Offset(1, 0)被注释,会导致Do While进入死循环,必须取消注释才能正常遍历。
内容的提问来源于stack exchange,提问作者Samuel Kinrade
相关产品推荐
相关产品推荐

