You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA中IF...Else语句执行异常问题排查求助

VBA的IF...Else语句问题排查

我编写了以下VBA脚本,预期执行效果如下:
预期效果截图

但实际运行后得到的结果却是这样:
实际效果截图

之后我把原代码里的Else部分替换成另一段IF+For Each的代码,脚本就能正常运行了。不过我更希望通过修改原代码的Else部分来解决问题,想请教一下我的IF...Else语句到底存在什么问题?

感谢解答!


原VBA脚本:

Sub VLOOKUP1()

    Dim WS As Worksheet
    Dim LastRow As Integer, x As Integer, j As Integer
    Set WS = Workbooks("Book2").Worksheets(2)
    LastRow = WS.Cells(WS.Rows.Count, 1).End(xlUp).ROW
    
    For x = 2 To LastRow
        For j = 2 To 6

            If WS.Cells(j, 8).Value = WS.Cells(x, 1) Then
    
                WS.Cells(j, 8).Offset(0, 1).Value = WS.Cells(x, 2).Value
                WS.Cells(j, 8).Offset(0, 2).Value = WS.Cells(x, 3).Value
                WS.Cells(j, 8).Offset(0, 3).Value = WS.Cells(x, 5).Value
                WS.Cells(j, 8).Offset(0, 4).Value = WS.Cells(x, 6).Value

            Else
                WS.Cells(j, 8).Offset(0, 1).Value = "NO DATA"
                WS.Cells(j, 8).Offset(0, 2).Value = "NO DATA"
                WS.Cells(j, 8).Offset(0, 3).Value = "NO DATA"
                WS.Cells(j, 8).Offset(0, 4).Value = "NO DATA"

            End If
        Next j
    Next x

End Sub

替换Else部分后的有效代码:

Dim Table As Range, CELL As Range
Set Table = Range("H1:L6")

For Each CELL In Table
    If CELL.Value = "" Then
        CELL.Value = "N/A"
        CELL.Font.Color = vbRed
    End If
Next CELL

内容的提问来源于stack exchange,提问作者PatrickThanksU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:01:23