简体   繁体   中英

Excel VBA calculate and set column width

I'm trying the center the range from B:AE in the center of the screen by adjusting the width of column A.

I'm able to change the width by adding the width as number instead of using AdjColWidth

Sub TestWH()

'Get widths
WinWidth = ActiveWindow.UsableWidth
RangeWidth = ActiveSheet.Range("B1:AE1").Width
AdjColWidth = WinWidth - RangeWidth / 2

'If less than 4 then set to 4
If AdjColWidth < 4 Then
    Range("A:A").ColumnWidth = 4
Else
    Range("A:A").ColumnWidth = AdjColWidth
End If

End Sub

Based on my comments, something like below should work. I worked out the ratio of points to columnwidth directly in the code, as this could change based on the font size of the normal style.

Sub TestWH()

'Get widths
WinWidth = ActiveWindow.UsableWidth

'work out the ratio between pixels and columnwidth
ratio = ActiveSheet.Columns(1).ColumnWidth / ActiveSheet.Columns(1).Width

RangeWidth = ActiveSheet.Range("B1:AE1").Width

'work out the size in columnwidth values
adjcolwidth = ((WinWidth - RangeWidth) / 2) * ratio

'If less than 4 then set to 4
If adjcolwidth < 4 Then
    Range("A:A").ColumnWidth = 4
ElseIf adjcolwidth < 255 Then
    Range("A:A").ColumnWidth = adjcolwidth
Else
    'what do you want to do if it's greater than 255?
End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM