我正在尝试创建一个宏,选择一组5个单元格的颜色 所以基本上它是: 透明,黄色,蓝色,透明,黄色,蓝色......
Sub ColorBanding()
Dim num As Integer
For i = 2 To 50
Dim range As String
range("A" + Str(i) + ":E" + Str(i)).Select
If i Mod 3 = 0 Then
Cells(1, 1).Select
' Yellow
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ElseIf i Mod 3 = 2 Then
' Blue
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End With
End If
Next i
End Sub
我遇到这条线路有问题: “range(”A“+ Str(i)+”:E“+ Str(i))。选择”
关于i = 2的评估示例: 输出:“A 2:E 2” 应该是:“A2:E2”
我得到的技术错误是: “期待一个数组”
有更好的方法吗? 有没有办法让这种方式正常工作?
答案 0 :(得分:0)
问题出在这里
Dim num As Integer
For i = 2 To 50
Dim range As String
range("A" + Str(i) + ":E" + Str(i)).Select
If i Mod 3 = 0 Then
Cells(1, 1).Select
range
是保留字,请勿将其用作变量名称,而应使用MyRange
之类的内容。range
,worksheet
等)只能在Set object = reference_to_other_object_of_the_same_type
语句中分配,请参阅下文。ActiveWorksheet
,ActiveWorksheet.Cells(1,1)
永久固定为单元格“A1”。另一方面,MyRange.Cells(1,1)可以移动。将其更改为:
Dim num As Integer
Dim MyRange as Range
Dim i as Integer
For i = 2 To 50
Set MyRange = range("A" & Str(i) & ":E" & Str(i))
MyRange.Select
If (i Mod 3) = 0 Then
MyRange.Cells(1, 1).Select
...
尚未测试代码,但我很确定它已经接近了。
答案 1 :(得分:0)
这是正确的语法。也不要选择/激活任何东西,因为它只会减慢速度。什么用'num'?
Sub test()
Dim num As Integer, MyRange As Range, i As Integer
For i = 2 To 50
Set MyRange = Range("A" & i & ":E" & i)
MsgBox MyRange.Address 'Delete this test line
With MyRange.Cells(1, 1).Interior
If (i Mod 3) = 0 Then
'Yellow
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
ElseIf i Mod 3 = 2 Then
'Blue
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End If
End With
Next i
End Sub