VBA: Set column widths

FryGirl

Well-known Member
Joined
Nov 11, 2008
Messages
1,360
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
I found the post below, but was hoping this could be done a manner where the array is written left-to-right versus up and down.

As this is it works for my needs after I expand the ar(1) out to ar(15), just hoping it could be shortened.

I'm starting with column A and setting out to column O with all different column widths.

Code:
[FONT=Verdana]https://www.mrexcel.com/forum/excel-questions/706877-set-column-widths-array-concept.html[/FONT]
[LEFT][COLOR=#333333][FONT=monospace]Sub cw()

Dim ar(1 To 3)
Dim c As Integer
Dim cnt As Integer

cnt = LBound(ar())

ar(1) = 20
ar(2) = 30
ar(3) = 40

For cnt = LBound(ar()) To UBound(ar())
    Columns(cnt).ColumnWidth = ar(cnt)
Next cnt

End Sub[/FONT][/COLOR][/LEFT]
 
Last edited:

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
Hi, you could try something like this..

Code:
Sub cw()


Dim c As Variant
Dim cnt As Integer


For Each c In Array(20, 30, 40, 30, 20, 10, 5, 20, 15, 5, 15, 12, 20, 15)
    cnt = cnt + 1
    Columns(cnt).ColumnWidth = c
Next c


End Sub
 
Upvote 0
Do you mean like this?
Code:
Dim ar As Variant
Dim cnt As Long

ar = Array(20,30,40)

For cnt = LBound(ar) To UBound(ar)
    Columns(cnt+1).ColumnWidth = ar(cnt)
Next cnt
 
Upvote 0
How about
Code:
Option Explicit
Sub FryGirl()
   Dim Ary As Variant
   Dim i As Long
   
   Ary = Array(20, 30, 40)
   For i = 0 To UBound(Ary)
      Columns(i + 1).ColumnWidth = Ary(i)
   Next i
End Sub
 
Upvote 0
Yes, thank you to all. This is exactly what I was looking for.
 
Upvote 0
Glad we could help & thanks for the feedback
 
Upvote 0

Forum statistics

Threads
1,213,551
Messages
6,114,272
Members
448,558
Latest member
aivin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top