简体   繁体   English

Excel VBA计算并设置列宽

[英]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. 我正在通过调整A列的宽度来尝试从屏幕中心的B:AE范围中心。

I'm able to change the width by adding the width as number instead of using AdjColWidth 我可以通过将宽度添加为数字而不是使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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