使用for循环来设置VBA中列宽的范围

在这里输入图像说明

我想能够使用某种循环来设置在Excel表中的列宽,所以我不必input每一列我想改变的宽度。 在这个图片的情况下,我希望所有的黑色列的宽度为0.92,绿色为0.83,橙色为7.29,我希望这些继续超过我​​在这里显示的设置范围。 以下是我使用的通用代码,但正如我所说的,我不想input每一列来改变宽度。

sub Set_Column_Width Range("E:E, I:I, M:M, Q:Q, U:U, Y:Y, AC:AC, AG:AG, AK:AK, AO:AO, AS:AS, AT:AT, AX:AX").ColumnWidth = 0.92 Range("G:G,K:K,O:O,S:S").ColumnWidth = 0.83 Range("F:F, H:H, J:J, L:L").ColumnWidth = 7.29 End sub 

如果你正在做一个模式,黑橙色,绿色,橙色,你可以循环。

 for i = [first column] to [last column] step 4 Columns(i).ColumnWidth = 0.92 Columns(i+1).ColumnWidth = 7.29 Columns(i+2).ColumnWidth = 0.83 Columns(i+3).ColumnWidth = 7.29 next i 

使用Columns(index)

 Dim i As Long For i = 5 To 105 Step 4 Columns(i).Columwidth = 0.92 next i For i = 6 To 106 Step 2 Columns(i).Columwidth = 7.29 next i For i = 7 To 107 Step 4 Columns(i).Columwidth = 0.83 next i 

另一种方法是根据索引确定宽度

 For i = 5 To 100 'find you what width this column should have Columns(i).Columnwidth = x next i 

这是假定宽度不是由颜色定义的,而是由它们的位置决定的

虽然我不确定这些颜色是什么,但很容易find。 如果整列是相同的颜色,你可以循环通过列,看第1行

 for i = 1 to 1000 'or whatever your last column is if cells(1, i).interior.color = rgb(255, 0, 0) then 'red, for example cells(1, i).columnwidth = 0.83 'or whatever the column width needs to be here else if cells(1, i).interior.color = rgb(...) then 'next color cells(1, i).columnwidth = ... 'etc. end if next i