Read and Write Column Width Function

Status
Not open for further replies.

jstiene

Board Regular
Joined
Aug 5, 2005
Messages
223
Since I constantly find myself tweaking column widths after running routines, I thought I would just write code that writes column code. Basically if a sheet is the way you want it, you determine the header row (just for commenting purposes) and run this to build code that figures out all your column widths in that sheet along with a comment about header value of each column. Obviously you shouldn't keep using the Sub name it creates, but change them for every sheet.

Sub ReadColumnWidths()
Dim g As Integer, LastCol As Integer, Val1 As String
Dim St1 As String, St2 As String, Add1 As String
Dim ColWidth As Integer, HeaderRow As Integer
HeaderRow = 1 'ActiveCell.Row
LastCol = ActiveSheet.UsedRange.Columns.Count
For g = 1 To LastCol
Add1 = Cells(HeaderRow, g).Address(False, False)
ColWidth = Range(Add1).ColumnWidth
Val1 = Range(Add1).Value
St1 = "Range(" & Chr(34) & Add1 & Chr(34) & ").ColumnWidth = " & ColWidth & " '" & Val1
St2 = St2 & vbCr & St1 'debug.print St1
Next g
St2 = vbCr & "Sub FormatColumns()" & vbCr & St2 & vbCr & vbCr & "End Sub"
Debug.Print St2 'MsgBox St2
End Sub

It spits out something like this into the immediate window:

Sub FormatColumns()

Range("A1").ColumnWidth = 15 'Name
Range("B1").ColumnWidth = 12 'Week Starting
Range("C1").ColumnWidth = 28 'Code
Range("D1").ColumnWidth = 55 'Project Name

End Sub
 

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.
Status
Not open for further replies.

Forum statistics

Threads
1,224,823
Messages
6,181,180
Members
453,021
Latest member
Justyna P

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