Excel VBA:运行时1004使用Union将范围添加到预先存在的范围(它们#39;重新放在同一张纸上!)

时间:2014-08-05 20:01:30

标签: excel vba

Excel VBA: 我尝试使用Application.Union将范围添加到预先存在的范围。每次联盟进行尝试时,我都会得到运行时错误1004.踢球者是因为范围在同一张纸上,所以我不知所措。

神奇发生在嵌套FOR循环中的IF块中。我已经为上下文包含了更多代码。任何帮助将不胜感激!

代码示例:

'---------------------------------------
'Get range of battle1 IDs from Sessions
'---------------------------------------
Dim ws As Worksheet: Set ws = objSessionsWB.ActiveSheet
Set rngBattleIDs = ws.Range("E3", ws.Range("E3").End(xlDown))

'---------------------------------------------------------
'Get range of battles from Battles that match battle1 IDs
'---------------------------------------------------------
Set ws = objBattlesWB.ActiveSheet

Dim rngBattleStats As Range
Dim bRow As Range

For Each battle In ws.Range("A3", ws.Range("A3").End(xlDown))
    For Each battleID In rngBattleIDs
        If battleID.Value = battle.Value Then

            'Get row containing battle1 info
            Set bRow = ws.Range(battle.End(xlToLeft), battle.End(xlToRight))

            'Use Union to add additional rows to range
            If rngBattleStats Is Nothing Then
                Set rngBattleStats = bRow
            Else
                Set rngBattleStats = Union(rngBattleStats, bRow)
            End If

        End If
    Next
Next

1 个答案:

答案 0 :(得分:2)

看起来问题不在我的问题范围内。该脚本正在workbook1中运行,但我正在使用的范围是在workbook2中。解决方案是从工作簿2运行Union:

Set rngBattleStats = workbook2.Application.Union(rngBattleStats, bRow)