Excel VBA计算并设置列宽

时间:2015-12-23 16:44:06

标签: excel vba excel-vba

我通过调整A列的宽度来尝试从屏幕中心的B:AE范围中心。

我可以通过将宽度添加为数字而不是使用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

1 个答案:

答案 0 :(得分:2)

根据我的评论,下面的内容应该有效。我直接在代码中计算了点与列宽的比率,因为这可能会根据正常样式的字体大小而改变。

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