简体   繁体   English

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

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

在此处输入图片说明

I want to be able to use some sort of for loop to set column widths in an excel sheet so I don't have to type out each column I want to change the width of. 我希望能够使用某种for循环在Excel工作表中设置列宽,因此我不必键入要更改其宽度的每一列。 In the case of this picture, I want all black columns to have a width of 0.92, green to be 0.83, and orange to be 7.29, and I want these to continue past what I've shown here for a set range. 在这张照片的情况下,我希望所有黑色列的宽度为0.92,绿色为0.83,橙色为7.29,并且我希望这些列继续超出此处所示的设定范围。 Below is the general code I used, but like I said, I don't want to have to type out every column to change the width. 下面是我使用的常规代码,但是就像我说的那样,我不想键入每一列来更改宽度。

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

If you are doing a pattern, black-orange-green-orange you can loop so. 如果您正在制作图案,黑色,橙色,绿色,橙色可以循环播放。

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

Use Columns(index) 使用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

The other way would be to determine the width based on the index 另一种方法是根据索引确定宽度

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

This is assuming the widths are not defined by the colors but by their position 假设宽度不是由颜色定义的,而是由它们的位置定义的

While I'm not sure what those colors are, it would be easy enough to find out. 虽然我不确定这些颜色是什么,但找出它很容易。 If the entire column is the same color, you could just loop through the columns and look at row 1. Something like 如果整列是相同的颜色,则可以遍历各列并查看第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