我有用于库存控制的用户表单,用于输入或输出项目,我想要修改下面的代码以显示它旁边的每个项目名称代码以进行搜索项目。 代码:
Private Sub ComboBox1_Click()
Dim i As Integer
Dim j As Integer
Dim final As Integer
Dim FINAL2 As Integer
For i = 2 To 1000
If Hoja5.Cells(i, 1) = "" Then
final = i - 1
Exit For
End If
Next
For i = 2 To 1000
If Hoja6.Cells(i, 1) = "" Then
FINAL2 = i - 1
Exit For
End If
Next
For i = 2 To final
If ComboBox1 = Hoja5.Cells(i, 1) Then
TextBox1 = Hoja5.Cells(i, 2)
Exit For
End If
Next
For j = 1 To FINAL2
If ComboBox1 = Hoja6.Cells(j, 1) Then
TextBox8 = Hoja6.Cells(j, 3)
Exit For
End If
Next
End Sub
Private Sub ComboBox1_Enter()
Dim i As Integer
Dim j As Integer
Dim H As Integer
Dim final As Integer
Dim tareas As String
ComboBox1.BackColor = &H80000005
For i = 1 To ComboBox1.ListCount
ComboBox1.RemoveItem 0
Next i
For j = 2 To 1000
If Hoja5.Cells(j, 1) = "" Then
final = j - 1
Exit For
End If
Next
For H = 2 To final
tareas = Hoja5.Cells(H, 1)
ComboBox1.AddItem (tareas)
Next
'End If
End Sub
表明所需修改的照片
我希望它像:
示例文件
答案 0 :(得分:2)
要执行此操作:
答案 1 :(得分:2)
您需要指定ColumnCount
值,并为List
属性提供数组。如果需要,您也可以指定一个字符串,其中包含ColumnWidths
属性的以逗号分隔的列宽列表:
Option Explicit
Public Sub PopulateComboBox(ByVal source As Range, Optional ByVal valueColumn As Long = 1, Optional ByVal hasHeader As Boolean = True)
With Me.ComboBox1
.ColumnCount = source.Columns.Count
.ColumnWidths = GetColumnWidths(source)
.ListWidth = IIf(ComboBox1.Width > source.Width, ComboBox1.Width, source.Width)
.List = source.Range(source.Rows(IIf(hasHeader, 2, 1)).EntireRow, source.Rows(source.Rows.Count).EntireRow).Value
.BoundColumn = valueColumn
End With
End Sub
Private Function GetColumnWidths(ByVal source As Range) As String
Dim cols As Long
cols = source.Columns.Count
Dim widths()
ReDim widths(1 To cols)
Dim col As Long
For col = 1 To cols
widths(col) = source(, col).Width
Next
GetColumnWidths = Join(widths, ",")
End Function
假设您在工作表上有ListObject
:
与UserForm1
实例一起使用的代码负责调用PopulateComboBox
方法:
Option Explicit
Sub Test()
With New UserForm1
.PopulateComboBox Sheet1.ListObjects(1).Range
.Show vbModal
End With
End Sub
通常,您希望ComboBox.Text
具有用户友好性,ComboBox.Value
是有用的东西 - 比如某些ID值:
这样做的问题是ComboBox
将始终使用其源中第一列的内容进行显示,因此您可以得到:
解决方案只是隐藏第一列(即将其宽度设置为0
):
由于valueColumn
是1
,Me.ComboBox1.BoundColumn
指的是隐藏的ID列,所以当我们这样做时:
Private Sub ComboBox1_AfterUpdate()
If Not IsNull(ComboxBox1.Value) Then Debug.Print ComboBox1.Value, ComboBox1.Text
End Sub
选择指环王后,这是在直接面板中打印的内容:
1 Lord of the Rings
ComboBox1.Value
为1
,ComboBox1.Text
为Lord of the Rings
:现在您的其余代码无需处理字符串文字!
答案 2 :(得分:1)
此代码将填充组合框并调整其设置以显示您的产品。如果您使用它,您将无法在组合框中添加或删除项目。您必须编辑工作表上的实际列表。
.RowSource = "OFFSET(PRODUCT!$A$1,1,0,COUNTA(PRODUCT!$A:$A)-1,3)"
将组合框的列表链接到工作表上的动态列表。随着该清单,它将会逐渐增长。.ColumnCount = 3
将Combobox设置为显示3列.ColumnWidths = "100pt;100pt;200pt"
设置每列的宽度.ListWidth = "400pt"
设置下拉列表的宽度。我把它做得比实际的组合框大。Private Sub UserForm_Initialize()
With ComboBox1
.RowSource = "OFFSET(PRODUCT!$A$1,1,0,COUNTA(PRODUCT!$A:$A)-1,3)"
.ColumnCount = 3
.ColumnWidths = "100pt;100pt;200pt"
.ListWidth = "400pt"
End With
End Sub