Excel 查找并选择在组合框列表中找到的项目
在下面的代码中,我检查Sheet2单元格Excel 查找并选择在组合框列表中找到的项目,excel,vba,combobox,userform,Excel,Vba,Combobox,Userform,在下面的代码中,我检查Sheet2单元格A1的值是否包含在combobox1列表中,如果找到,则将其置于“选择模式”。但它不起作用。应该更正代码的哪一部分 Private Sub UserForm_Initialize() Set xRg = Worksheets("Sheet1").Range("A1:B5") Me.ComboBox1.List = xRg.Columns(1).Value End Sub Private Sub CommandButton1_Click() D
A1
的值是否包含在combobox1列表中,如果找到,则将其置于“选择模式”。但它不起作用。应该更正代码的哪一部分
Private Sub UserForm_Initialize()
Set xRg = Worksheets("Sheet1").Range("A1:B5")
Me.ComboBox1.List = xRg.Columns(1).Value
End Sub
Private Sub CommandButton1_Click()
Dim foundRng As Range
Set findrange = Sheets("Sheet1").Range("A1:B5")
Set foundRng = findrange.Find(Sheets("Sheet2").Range("A1"))
If foundRng Is Nothing Then
MsgBox "Nothing found"
Else
MsgBox "I Found"
Me.ComboBox1.ListIndex = foundRng.Value
End If
End Sub
声明变量并提供正确的数据类型 我没有对您的代码做太多更改,但想给您一些提示:
选项Explicit
以强制自己声明变量(对象)表格2中提供输入案例!A1
单元格,如果将字符串或空字符串(而不是数字)与列表索引
数字进行比较,则可能会发生类型不匹配工作表
Option Explicit ' declaration head of your UserForm code module
Dim xrg As Range ' possibly declared here to be known in all UserForm procedures
Private Sub UserForm_Initialize()
Set xrg = ThisWorkbook.Worksheets("Sheet1").Range("A1:B5") ' << fully qualified range reference (fqrr)
Me.ComboBox1.List = xrg.Columns(1).Value
End Sub
Private Sub CommandButton1_Click()
Dim foundRng As Range, findrange As Range
Set findrange = ThisWorkbook.Worksheets("Sheet1").Range("A1:B5") ' fqrr
Set foundRng = findrange.Find(Thisworkbook.Worksheets("Sheet2").Range("A1")) ' fqrr
If foundRng Is Nothing Then
MsgBox "Nothing found"
Me.ComboBox1.ListIndex = -1
ElseIf foundRng.Value = vbNullString Then
MsgBox "Empty search item"
Me.ComboBox1.ListIndex = -1
Else
MsgBox "1 item found"
If IsNumeric(foundRng.Value) Then
Me.ComboBox1.ListIndex = CLng(foundRng.Value) + 1
Else
Me.ComboBox1.ListIndex = foundRng.Row - 1
End If
End If
End Sub
祝未来的学习步骤好运:-)嗨,亲爱的朋友T.M。!谢谢你的完整解释。我很高兴你喜欢我像你一样进步。在询问的代码文本中,只需将
Me.ComboBox1.ListIndex=foundRng.Value
更改为Me.ComboBox1.ListIndex=foundRng.Row-1
。只有这个。很高兴。我将单元格的值更改为.Range(“A:B”)
。但在组合框列表的末尾,它还列出了所有空行。如何不显示这些空白值?我测试了代码.End(xlUp)
,但失败了。由于注释,我编辑了答案-顺便说一句,在SO(堆栈溢出)有大量的工作编码示例涉及这方面。因此,如果您对.End(xlUp)
有问题,最好发布不起作用的完整代码部分,否则只能做出假设。尽管如此,我希望已经帮助了-:)@FirstLast
Private Sub UserForm_Initialize()
Dim n& ' ... As Long
With ThisWorkbook.Worksheets("Sheet1")
n = .Range("A" & .Rows.Count).End(xlUp).Row
Set xrg = .Range("A1:B" & n) ' << fully qualified range reference
End With
Me.ComboBox1.List = xrg.Columns(1).Value
End Sub