VBA新手,并在Excel中使用它。
我有一个User表单,我正在尝试使用查找从ComboBox3中输入的值填充TextBox4。我有以下编译的代码,但它产生的msgbox表示字符串无法找到...
Private Sub ComboBox3_Change()
Dim strFind As String
Dim rFound As Range
ws = "Year-to-Date Summary"
If ComboBox3.ListIndex > -1 Then
strFind = ComboBox3
On Error Resume Next
With ws.Column(2, 3)
Set rFound = .Find(What:="strFind", After:=.Cells(39, 49), _
LookIn:=.Cells(39, 49), LookAt _
:=.Cells(39, 49), SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:= False)
End With
If rFound Is Nothing Then
MsgBox strFind & " cannot be found"
Exit Sub
Else
TextBox4 = rFound(1, 2)
End If
End If
End Sub
我也尝试了Vlookup,但是这个错误信息......
Private Sub ComboBox3_Change()
TextBox4.Text = WorksheetFunction.VLookup(Val(ComboBox3.Text), _
Sheets("Year-to-Date Summary").Range("C39:C49" & LastRow), 2, False)
End Sub
答案 0 :(得分:1)
Set
请参阅此示例( UNTESTED )
Private Sub ComboBox3_Change()
If ComboBox3.ListIndex = 0 Then Exit Sub
Dim strFind As String
Dim ws As Worksheet
Dim rFound As Range
Set ws = ThisWorkbook.Sheets("Year-to-Date Summary")
strFind = ComboBox3.Value
Set rFound = ws.Columns(3).Find(What:=strFind, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not rFound Is Nothing Then
TextBox4 = rFound.Offset(,1)
Else
MsgBox strFind & " cannot be found"
End If
End Sub
如果您的范围已修复,请在上面的代码中将ws.Columns(3)
更改为ws.Range("C39:C49")
。
如果您想使用工作表功能,那么您(已审判和测试)
注意:我没有在下面的代码中使用错误捕获。我相信你可以照顾到这一点。
Private Sub ComboBox3_Change()
If ComboBox3.ListIndex = 0 Then Exit Sub
TextBox4.Text = Application.WorksheetFunction.VLookup( _
Val(ComboBox3.Value), _
Sheets("Year-to-Date Summary").Range("C39:D49"), _
2, _
False _
)
End Sub
注意我们在第一个示例中如何使用C39:C49 / Columns(3) + Offset
以及我们如何在第二个示例中使用C49:D49
编辑:我忘记评论On Error Resume Next
除非有必要,否则请勿使用。这就像告诉代码“闭嘴!”如果发现错误:)
答案 1 :(得分:0)
你的ws显然是一个字符串,它没有.column属性
将行ws = "Year-to-Date Summary"
替换为
set ws = worksheets("Year-to-Date Summary")
并查看是否有帮助。
您是否确保每个模块都有“Option Explicit
”且您的应用成功编译?你会发现我认为这个错误。
答案 2 :(得分:0)
Private Sub ComboBox3_Change()
TextBox4.Text = WorksheetFunction.VLookup(Me.ComboBox3.Text, Sheets("Year-to-Date Summary").Range("$B$39:$C$49"), 2, False)
TextBox3.Text = WorksheetFunction.VLookup(Me.TextBox4.Text, Sheets("Year-to-Date Summary").Range("$C$39:$D$49"), 2, False)
End Sub
这对我有用,可以从组合框中做两个文本框
答案 3 :(得分:-1)
Private Sub ComboBox3_Change()
Dim strFind As String
Dim rFound As Range
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Year-to-Date Summary")
If ComboBox3.ListIndex > -1 Then
strFind = ComboBox3.text
On Error Resume Next
'编辑删除整个vlookup部分...... '添加循环以搜索范围内的文本
Set rSearch = ws.Range("B:C")
For Each rFound In rSearch
If rFound.Value = strFind Then
TextBox4.Text = rFound.value
else
MsgBox strFind & " cannot be found"
Exit Sub
End If
Next rFound
End Sub