我有一个可以格式化多页 Excel 文档的宏。每张纸上都有一个数据表,我尝试根据标题行(第 1 行)的内容对各列进行颜色编码。
我想选择列中的第二个单元格,直到最后一行数据,并设置背景颜色。我目前有一些看起来像这样的东西:
For Each ws In ActiveWorkbook.Worksheets
With ws
.Activate
' Convert to table
If .UsedRange.ListObject Is Nothing Then
.ListObjects.Add SourceType:=xlSrcRange,
Source:=.UsedRange,
xllistobjecthasHeaders:=xlYes,
TableStyleName:="Table Style 1"
End If
' Additional Formatting
...
' Adjust columns
For Each col In .UsedRange.Columns
Header = col.Cells(1, 1)
' Additional formatting that works
...
Dim col_color As Variant
' Color Code
If Header = "A" Then
col_color = xlThemeColorAccent6 ' Orange
ElseIf Header ="B" Then
col_color = xlThemeColorLight2 ' Blue
ElseIf Header = "C" Then
col_color = xlThemeColorAccent4 ' Purple
ElseIf Header ="D" Then
col_color = xlThemeColorAccent3 ' Green
ElseIf Header = "E" Then
col_color = xlThemeColorAccent2 ' Red
End If
Range(col.Cells(2, 1)).Select ' ERROR HERE
Range(Selection, Selection.End(xlDown)).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = col_color
.TintAndShade = 0.8
.PatternTintAndShade = 0
End With
Next col
我在 Range(col.Cells(2, 1)).Select
上收到以下错误:“对象 '_Global' 的方法 'Range' 失败”。
我的问题是如何在循环的当前列迭代中正确选择第二个单元格?
最佳答案
I would like to select the 2nd cell in the column, up to the last row of data, and set the background color.
无需进行选择
来设置背景颜色。正确声明范围变量并使用它:
Dim formatRange as Range
Set formatRange = Range(col.Cells(2, 1), col.Cells(2, 1).End(xlDown) )
With formatRange.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = col_color
.TintAndShade = 0.8
.PatternTintAndShade = 0
End With
发生错误是因为您只向 Range
方法传递了一个参数,该参数是一个单元格,其默认属性是它的 Value
,所以除非col.Cells(2,1)
包含有效范围地址字符串作为其值,这总是会失败。您可以通过在单个Select
中将两个参数传递给Range
来避免这种情况:
Range(col.Cells(2, 1), col.Cells(2, 1).End(xlDown)).Select
With Selection.Interior
...
或者:
col.Cells(2, 1).Select
Range(Selection, Selection.End(xlDown)).Select
With Selection.Interior
...
或者甚至:
col(2,1).Select
Range(Selection, Selection.End(xlDown)).Select
With Selection.Interior
...
但是你不应该做这些事情:
这几乎是普遍的better to avoid Activate/Select .
关于vba - 在 VBA 中循环列时选择单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51990740/