在我的Excel电子表格中,我使用下面的VBA代码使用UserForm
中的值获得一个ComboBox
和一个Sheet1
:
电子表格上的 ComboBox1 列表:
A B C
1 Q1
2 January
3 February
4 March
5 Q2
6 April
7 May
8 June
要调用 UserForm1(已连接到电子表格上的按钮)的VBA代码:
Sub Test()
Call UserForm1.Show(vbModeless)
End Sub
UserForm1 的VBA代码:
Private Sub UserForm_Activate()
ComboBox1.List = Sheet1.Range("A1:A8").Value
End Sub
最后, UserForm1 看起来像这样:
到目前为止,所有这些都工作正常。
您可以在电子表格的原始列表中看到month
下面的quarters
是缩进的。
是否还可以缩进 UserForm1 的 ComboBox1 中的值?
答案 0 :(得分:4)
您可以通过工作表中的putting a space before the values
解决问题,然后使用以下VBA选项之一:
选项1:
组合框的VBA:
Private Sub UserForm_Activate()
ComboBox1.List = Sheet1.Range("A1:A8").Value
End Sub
VBA,将没有空格的选定值插入电子表格:
(为了在电子表格中进一步使用它们)
Sub ComboBox1_Insert_Value()
Sheet1.Range("E1").Value = Trim(ComboBox1.Value)
End Sub
选项2:
组合框的VBA:
遍历范围并检查水平方向是否设置为正确。如果是这样,则可以在单元格的值之前添加一个空格。
Private Sub UserForm_Activate()
For Each cell In Range("A1:A8")
If cell.HorizontalAlignment = xlRight Then
ComboBox1.AddItem " " & cell.Value
Else
ComboBox1.AddItem cell.Value
End If
Next cell
End Sub
VBA,将没有空格的选定值插入电子表格:
(为了在电子表格中进一步使用它们)
Sub ComboBox1_Insert_Value()
Sheet1.Range("E1").Value = Trim(ComboBox1.Value)
End Sub
答案 1 :(得分:4)
根据我的评论,您可以在组合框中使用多个列,并根据需要调整列宽。例如
Private Sub ComboBox1_Click()
Debug.Print ComboBox1.Value
With ComboBox1
If .Value <> vbNullString Then
.Text = Split(.Value, "-")(1)
End If
End With
End Sub
Private Sub UserForm_Initialize()
Dim rng As Range
Dim Quarter As String
Dim c
With Sheet1
Set rng = .Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
End With
With ComboBox1
.ColumnCount = 3
.ColumnWidths = "0;20;40"
For Each c In rng
If c.HorizontalAlignment = xlRight Or c.IndentLevel > 0 Or Len(c.Value2) > Len(LTrim(c.Value2)) Then
.AddItem Quarter & "-" & c.Value2
.Column(2, .ListCount - 1) = c.Value2
Else
Quarter = c.Value2
.AddItem vbNullString
.Column(1, .ListCount - 1) = Quarter
End If
Next c
End With
End Sub
这可以同时使用三列。第一个对最终用户隐藏,用作行ID值(Quarter
和month
的组合),第二列保存Quarter
值,第三列保存{{ 1}}值
产生: