如果我创建一个 Excel VBA 用户表单,该表单动态生成可变数量的控件,我该如何确定表单的可用区域,以便我可以调整表单大小以适合控件?
下面附上了一张截图,后面是代码示例,但最后几行代码不起作用。
我可以为 UserForm_Initialize() 编写自己的自动调整大小代码,但如果找不到表单可用的宽度和高度,就无法实现。这总是会存在差异,这无疑包括边框、阴影、标题栏等的尺寸。
我确实知道 VBA 中各种测量尺度(例如像素、缇、英寸等)比较混乱。因此,如果任何答案指定了所使用的尺度,那将会很有帮助,这样我就可以调用正确的转换函数。
我确实找到了有关 VBA 坐标系的这篇帖子,它很有帮助,但它没有回答我的问题: https://www.reddit.com/r/vba/comments/1arzvx8/coordinate_systems_in_vba_userform_controls/
Private Sub UserForm_Initialize()
Dim ctls As MSForms.Controls
Dim ctl As MSForms.Control
Dim coll As VBA.Collection
Dim ctlCount As Integer
Dim colCount As Integer
Dim x As Single
Dim y As Single
Dim w As Single
Dim h As Single
Dim i As Integer
'Settings.
colCount = 5
w = 24
h = 24
'Get the objects.
Set ctls = Me.Controls
Set coll = New VBA.Collection
'Add the buttons to a collection.
ctlCount = ctls.Count
For i = 0 To ctlCount - 1
For Each ctl In ctls
If ctl.TabIndex = i Then
coll.Add ctl
End If
Next
Next
'Align the buttons.
i = 0
Do
If i < ctlCount Then
y = y + 1
Do
x = x + 1
If x <= colCount Then
i = i + 1
Set ctl = coll.Item(i)
ctl.Left = (x - 1) * w
ctl.Top = (y - 1) * h
ctl.Width = 24
ctl.Height = 24
Else
Exit Do
End If
Loop
x = 0
Else
Exit Do
End If
Loop
'Adjust the form size.
Me.Width = (x + 1) * w '### This does not work. ###
Me.Height = (y + 1) * h '### This does not work. ###
End Sub