我正在尝试使用此answer来将自己的活动单元格地址添加到某个范围,以便稍后可以选择整个范围以应用条件格式。下面是我的代码,但是我不确定是什么错误。出现错误“编译错误:类型不匹配”
p / s:我已经在此特定单元格上记录了宏,然后对其进行了编辑。
Sub Macro1()
Dim rng2 As Range
Range("B3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("D3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("F3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("H3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("J3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("L3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("N3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("P3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("R3").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("R7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("P7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("N7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("L7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("J7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("H7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("F7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("D7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("B7").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("B11").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("D11").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("F11").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range("J11").Select
Set rng2 = Union(rng2, ActiveCell.Address)
Range(rng2).Select
End Sub
答案 0 :(得分:1)
Set rng2 = Union(rng2, ActiveCell.Address)
应该是Set rng2 = ActiveCell
。在将其设置为某对象之前,您无法将其合并为空对象,而rng2也将成为空对象。Set rng2 = Union(rng2, ActiveCell.Address)
应该是Set rng2 = Union(rng2, ActiveCell)
。您不能联合到范围对象的字符串地址。您必须合并到范围对象。Range(rng2).Select
无效;只需使用rng2.Select
。出于所有意图和目的,您可能只是说过
Range("B3, D3, F3, H3, J3, L3, N3, P3, R3, R7, P7, N7, L7, J7, H7, F7, D7, B7, B11, D11, F11, J11").Select
您在评论中提到,由于空间限制,您已切断了代码。考虑以下循环。
dim i as long, rng2 as range
Set rng2 = Range("B3, D3, F3, H3, J3, L3, N3, P3, R3")
For i = 7 To 23 Step 4
Set rng2 = Union(rng2, Intersect(rng2.EntireColumn, Rows(i)))
Next i
rng2.select
rng2.interior.color = vbred
Debug.Print rng2.Address(0, 0)
'B3,D3,F3,H3,J3,L3,N3,P3,R3,B7,D7,F7,H7,J7,L7,N7,P7,R7,B11,D11,F11,H11,J11,L11,N11,P11,R11,B15,D15,F15,H15,J15,L15,N15,P15,R15,B19,D19,F19,H19,J19,L19,N19,P19,R19,B23,D23,F23,H23,J23,L23,N23,P23,R23
debug.print消息进入VBE的Immediate window。