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

如何高效遍历指定工作表精简VBA代码 解决Union方法报错问题

报错根因

VBA 内置的 Union 方法仅支持合并同一工作表内的多个单元格区域,你当前的代码会把不同工作表(North/Central/South)的符合条件行都存入同一个rngU对象,跨工作表的区域无法执行合并操作,因此触发Method 'Union' of object '_Global' failed报错。

修复方案

每遍历完一个工作表后,立即将当前表收集的符合条件区域粘贴到目标表,随后清空重置rngU,保证每次Union操作合并的都是同一个工作表的区域,修改后完整代码如下:

Sub FD_Copy_Data_On_Condition()
    Dim ws As Worksheet, sh1 As Worksheet, LastRow As Long
    Dim arr_column, rngU As Range, i As Long, lastCol As Long
    
    Set sh1 = Sheet11
    
    For Each ws In Sheets(Array("North", "Central", "South")) ' 遍历指定工作表
        LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row    ' 动态获取当前表A列最后一行
        lastCol = ws.UsedRange.Columns.Count
        arr_column = ws.Range("U3:U" & LastRow).Value2
        
        ' 每次遍历新工作表前先重置rngU,避免和上一个表的区域混合
        Set rngU = Nothing
        
        For i = 1 To UBound(arr_column)
            If arr_column(i, 1) = "Yes" Then
                If rngU Is Nothing Then
                    Set rngU = ws.Range(ws.Cells(i + 2, 1), ws.Cells(i + 2, lastCol))
                Else
                    Set rngU = Union(rngU, ws.Range(ws.Cells(i + 2, 1), ws.Cells(i + 2, lastCol)))
                End If
            End If
        Next i
        
        ' 粘贴当前表的符合条件数据
        If Not rngU Is Nothing Then
            rngU.Copy Destination:=sh1.Range("A" & sh1.Rows.Count).End(xlUp).Offset(1)
        End If
    Next ws
End Sub
额外优化说明

原代码中LastRow = ws.Cells(Rows.count, 1).End(xlUp).Row的Rows.Count前面新增了ws.限定,避免当前激活工作表不是ws时,行数统计出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:27:05