查找并选择在组合框列表中找到的项目

时间:2018-10-11 16:21:51

标签: excel vba combobox userform

在以下代码中,我检查combobox1列表中是否包含Sheet2单元格A1的值,如果找到,将其置于'选择模式'中。但这行不通。该代码的哪一部分应该更正?

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

1 个答案:

答案 0 :(得分:1)

声明变量并提供正确的数据类型

我没有对您的代码进行太多更改,但是想给您一些提示:

  1. 设置Option Explicit来强迫自己声明变量(对象)。
  2. Sheet2!A1单元格中提供输入格,如果您将字符串或空字符串(而非数字)与ListIndex数字进行比较,则可能会发生类型不匹配。
  3. 建议完全限定范围引用(fqrr)
  4. 如果仅引用工作表,则优选使用术语Worksheets
  5. 检查堆栈溢出的Help Tour 关于How do I ask a good question?,并且, How to create a Minimal, Complete, and Verifiable example
  6. 尝试学习有关错误处理调试VBA 的知识,以便能够提供有关发生的错误的更精确信息。 “不起作用” 对于该站点上经验丰富的程序员来说,就像是一头红牛,在这里精确: ;

一些较小的更改...

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

推荐链接

您可以在Chip Pearson的站点上找到有关Debugging VBA的有用指南。

由于评论而产生的补遗

为了定义动态范围而又不跟随空行,您可以按以下方式重写Initialize过程:

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

祝您以后的学习步骤顺利:-)