繁体   English   中英

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

[英]Using for loop to set ranges of column widths in VBA

在此处输入图片说明

我希望能够使用某种for循环在Excel工作表中设置列宽,因此我不必键入要更改其宽度的每一列。 在这张照片的情况下,我希望所有黑色列的宽度为0.92,绿色为0.83,橙色为7.29,并且我希望这些列继续超出此处所示的设定范围。 下面是我使用的常规代码,但是就像我说的那样,我不想键入每一列来更改宽度。

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

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

虽然我不确定这些颜色是什么,但找出它很容易。 如果整列是相同的颜色,则可以遍历各列并查看第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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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