用户表单中的Vlookup无法正常工作,无法findstring

新的VBA,并在Excel中使用它。

我有一个用户表单,并且我正在尝试使用查找来填充ComboBox3中input的值的TextBox4。 我有下面的代码编译,但它是生产msgbox说,string不能find…

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,但是这个popup的错误信息…

 Private Sub ComboBox3_Change() TextBox4.Text = WorksheetFunction.VLookup(Val(ComboBox3.Text), _ Sheets("Year-to-Date Summary").Range("C39:C49" & LastRow), 2, False) End Sub 

  1. ws是一个变种。 您不要像这样分配工作表。 你必须使用Set
  2. strFind在引号内,所以它将被视为一个string

看到这个例子( 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")

如果你想使用工作表function,那么你这个( TRIED AND TESTED

注意 :我没有在下面的代码中使用错误捕获。 我相信你可以照顾。

 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永远不要使用它,除非需要。 就像告诉密码“闭嘴! 如果发现错误:)

你的ws显然是一个string,它没有.column属性。
用行replace行ws = "Year-to-Date Summary"
set ws = worksheets("Year-to-Date Summary") ,看看是否有帮助。

你确定每个模块都有一个“ Option Explicit ”,并且你的应用程序编译成功吗? 你会发现我认为的错误。

 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 

这对我来说,从combobox做两个文本框

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 

'编辑删除整个查找部分…'添加循环search范围内的文本

  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