【问题标题】:Using for loop to set ranges of column widths in VBA使用 for 循环在 VBA 中设置列​​宽范围
【发布时间】:2016-06-22 15:43:31
【问题描述】:

我希望能够使用某种 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

【问题讨论】:

  • 有什么规则可以用来做这个吗?即是什么决定了哪一列的宽度是多少?是颜色还是有图案?
  • 抱歉,颜色只是为了更好地突出我想要做的事情......它是我试图循环的图案而不是颜色

标签: vba excel for-loop range


【解决方案1】:

如果你正在做一个图案,黑橙绿橙你可以这样循环。

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

【讨论】:

  • 如果你把[]改为()并使用ii+1i+2i+3,这比我的要好;)
【解决方案2】:

使用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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 我喜欢这个答案,因为它考虑了颜色。它看起来像 OP 的列遵循一种模式,但没有任何保证,所以我会选择这个。
    • @BruceWayne。大概 OP 不想手动进行着色,然后使用宏来做宽度。哦,解释模棱两可的客户简报的乐趣:)
    • 没错。目前尚不清楚电子表格是否真的是彩色的,或者是否添加了颜色来说明图案。
    猜你喜欢
    • 2017-06-12
    • 1970-01-01
    • 2019-12-23
    • 2016-05-21
    • 2019-01-12
    • 2017-02-10
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多