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

如何修复VBA嵌套循环执行时出现的Run-Time Error '1004'错误

问题修复方案

错误根因

你遇到的1004报错核心是常量拼写错误:
代码中Range("A3").End(x1Down)里的x1Down使用了数字1,VBA内置的单元格定位常量实际为xlDown,其中的l是小写英文字母L,拼写错误导致系统无法识别常量,触发Range对象的End方法调用失败。

额外优化建议

除了拼写修正,还有几个可以优化的点避免后续出错:

  • 直接绑定工作表对象,避免使用Select、Activate这类依赖当前激活状态的方法,防止工作表切换后范围定位错误
  • 改用从下往上查找最后非空行的方式,避免A/B列存在空行时End(xlDown)提前截止,漏掉后续数据
  • 增加空值判断逻辑,避免输出无效的空名组合

修复后完整代码

Sub LoopsHW2()
    Dim ws As Worksheet
    Dim First As Range
    Dim Middle As Range
    Dim FirstOut As String
    Dim MidOut As String
    Dim oRow As Integer
    Dim lastA As Long, lastB As Long
    
    ' 绑定目标工作表,不需要选中激活
    Set ws = ThisWorkbook.Sheets("Sheet2")
    oRow = 2 ' 输出起始行
    
    ' 查找A列、B列最后一个非空行,从下往上找更稳定
    lastA = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    lastB = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
    
    ' 遍历所有非空的First名
    For Each First In ws.Range("A3:A" & lastA)
        FirstOut = First.Value
        ' 空值跳过,避免输出空的First组合
        If FirstOut <> "" Then
            ' 遍历所有非空的Middle中间名
            For Each Middle In ws.Range("B3:B" & lastB)
                MidOut = Middle.Value
                If MidOut <> "" Then
                    ws.Cells(oRow, "C").Value = FirstOut
                    ws.Cells(oRow, "D").Value = MidOut
                    oRow = oRow + 1
                End If
            Next
        End If
    Next
    Beep
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:45:03