簡體   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