简体   繁体   中英

Excel - VBA Merging cells on separate worksheet

I have sheet 1 active, and I'm trying to perform a merge operation on some cells in Sheet 2, but I'm getting a 'Method 'Range of object '_Worksheet' failed'' error.

Dim rawData As Worksheet

For i = 2 To 12 Step 2
    rawData.Range(Cells(2, i), Cells(2, (i + 1))).Merge
Next i 

However it does work if I insert a rawData.Activate line beforehand. Is there any way to accomplish this without activating the sheet first?

Range/Cells without a qualifying worksheet always refer to the activesheet (unless in a Worksheet code module, where they refer to that worksheet).

Using/relying on the default behavior (ie. relying on a certain sheet being active when your code runs) should be avoided whenever possible.

Dim rawData As Worksheet

With RawData
    For i = 2 To 12 Step 2
        .Range(.Cells(2, i), .Cells(2, (i + 1))).Merge
    Next i
End With 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM