在以下代码中,我检查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
答案 0 :(得分:1)
声明变量并提供正确的数据类型
我没有对您的代码进行太多更改,但是想给您一些提示:
Option Explicit
来强迫自己声明变量(对象)。Sheet2!A1
单元格中提供输入格,如果您将字符串或空字符串(而非数字)与ListIndex
数字进行比较,则可能会发生类型不匹配。Worksheets
。一些较小的更改...
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
祝您以后的学习步骤顺利:-)