【发布时间】:2014-08-11 19:18:00
【问题描述】:
我正在努力设置一个组合框(在 Excel VBA 中),使其宽度根据其包含的最长字符串的长度自动调整。
我正在尝试创建一个下拉列表(使用名为“WorksheetSelectionForm”的表单中的组合框),一旦打开特定的工作簿,它就会出现在屏幕上,并允许用户选择他们要使用的工作簿的哪个工作表希望打开。
我希望组合框的宽度调整为下拉列表中最长文本字符串的长度。目前我的下拉列表包含三个项目(工作簿中当前存在的工作表的名称)。它们是:
- “损益表”(23个字符)
- “资产负债表”(13 个字符)
- “现金流量报告”(15 个字符)
可以将更多工作表添加到工作簿中,从而将更多项目添加到下拉列表中,因此我不想简单地将组合框的宽度固定为 23 点(当前最长字符串的长度)下拉列表)。
我一直在参考来自 OzGrid 的以下线程以获得想法(参见条目 #3):http://www.ozgrid.com/forum/showthread.php?t=55098。他们提出的解决方案如下:
Dim iWidth As Double
ComboBox1.AutoSize = True
iWidth = 0
For i = 0 To ComboBox1.ListCount - 1
ComboBox1.ListIndex = i
If iWidth < ComboBox1.Width Then
iWidth = ComboBox1.Width
End If
Next
ComboBox1.Width = iWidth
ComboBOx1.AutoSize = False
ComboBox1.ListCount = 0
此解决方案的问题在于 if-then 语句中的代码 ComboBox1.Width 实际上似乎无法计算出当前在 for-next 循环中焦点所在的组合框项的长度。
下面是我目前写的代码:
Private Sub Workbook_Open()
Dim Sheet As Worksheet, CmBox As MSForms.ComboBox, LWidth As Double, i As Integer
Set CmBox = WorksheetSelectionForm.ComboBox_Worksheets
LWidth = 0
'Populate the drop-down list with the names of the worksheets
For Each Sheet In Worksheets
CmBox.AddItem Sheet.Name
Next Sheet
'Find out the length of the longest string in the combobox
For i = 0 To CmBox.ListCount - 1
CmBox.ListIndex = i
If Len(CmBox.Value) > LWidth Then
LWidth = Len(CmBox.Value)
End If
Next i
'Set the combobox's width to the length of the longest string in the combobox
CmBox.ListWidth = LWidth
'Show the form on screen
WorksheetSelectionForm.Show
End Sub
此代码在运行时似乎没有按需要设置组合框的宽度。它还会生成一个缺少其所有项目(工作表名称)的组合框。我哪里出错了?
以下是用户选择组合框中的项目时的代码(以防万一它对您有用):
Private Sub ComboBox_Worksheets_Change()
'Activate the worksheet whose name has been selected in the combobox
Sheets(ComboBox_Worksheets.Value).Activate
'Close the form
Unload WorksheetSelectionForm
End Sub
【问题讨论】:
-
hence why I don't want to simply fix the combobox's width at 23 pointsTom 已经为您提供了一个非常好的开始链接。但是,如果您不想了解代码的复杂性,那么这里是另一种选择。可以进入工作表命名的最大字符是 32。为什么不默认将其设置为保持字体和大小的宽度。这种方法的唯一问题是您必须记住您的应用可能遇到的不同屏幕分辨率...