VBA窗体 – Vlookup单元格,并为该单元格赋值

在VBA中遇到一个关于vlookup函数的问题。

我有2个combobox和6个文本框供用户input。

我想使用一个查找(或索引,匹配(),匹配())在数据表中查找单元格,并将文本框中的值分配给这些单元格。

当我运行我认为应该工作的代码时,它返回对象错误。

Private Sub CommandButton2_Click() Dim MonthlyTable As Range Set MonthlyTable = Sheets("DATA Monthly").Range("A6:AE400") Dim ColumnRef As Range Set ColumnRef = Sheets("Drivers").Range("N11") ' Assign CB2 value to M11 cell reference so it can be converted to a column ref in N11. Sheets("Drivers").Range("M11").Value = ComboBox2.Value Dim CB1Value As String CB1Value = "Joiners" & ComboBox1.Value Dim CB2Value As String CB2Value = ComboBox2.Value MsgBox CB1Value & " " & CB2Value Dim tb1value As Range tb1value = Application.WorksheetFunction.VLookup(CB1Value, MonthlyTable, ColumnRef, False) tb1value.Value = TextBox1.Value Unload Me End Sub 

我不知道该怎么做,因为我觉得应该这么简单!

提前致谢。

编辑。 进一步的挖掘表明,你不能select一个你正在查看的单元格,因为这个命令只返回一个值,它实际上并没有为我的意图和目的select单元格。

我不是很清楚你的实际目标,而只是跟随你的愿望,如下所述:

我想使用一个vlookup(或索引,匹配(),匹配())在数据表中查找单元格,并将文本框中的值分配给这些单元格

你可能要采用以下技术:

 Dim tb1value As Variant '<--| a variant can be assigned the result of Application.Match method and store an error to be properly cheeked for tb1value = Application.Match(CB1Value, MonthlyTable.Column(1), 0) '<--| try finding an exact match for 'CB1Value' in the first column of your data range If Not IsError(tblvalue) Then MonthlyTable(tb1value, columnRef.Value).Value = TextBox1.Value '<--| if successful then write 'TextBox1' value in data range cell in the same row of the found match and with `columnRef` range value as its column index 

Excel使用工作表函数来处理数据,VBA具有不同的工具,当您发现自己通过VBA设置单元格值时,一些工作表函数可以引用它们,现在是时候寻找一个真正的VBA解决scheme。 我build议下面这个,顺便说一句,你可能会考虑在Cbx2的Change事件上运行而不是命令button。

 Private Sub Solution_Click() ' 24 Mar 2017 Dim MonthlyTable As Range Dim Rng As Range Dim Lookup As String Dim Done As Boolean Set MonthlyTable = Sheets("DATA Monthly").Range("A2:AE400") ' take the lookup value from Cbx1 Lookup = ComboBox1.Value Set Rng = MonthlyTable.Find(Lookup) If Rng Is Nothing Then MsgBox Chr(34) & Lookup & """ wasn't found.", vbInformation, "Invalid search" Else With ComboBox2 If .ListIndex < 0 Then MsgBox "Please select a data type.", vbExclamation, "Missing specification" Else TextBox1.Value = MonthlyTable.Cells(Rng.Row, .ListIndex + 1) Done = True End If End With End If If Done Then Unload Me End Sub 

有两点需要说明。 首先,表单在被拒绝的条目之后不会closures。 你将不得不添加一个取消button,以避免不必要的循环,用户不能离开表单,直到他input正确的东西。 请注意,只有在findsearch条件时, Done才被设置为真。返回一个值,直到Done = True ,表单才会被closures。

其次,观察使用Cbx2的ListIndex属性。 该Cbx下拉菜单中的所有项目都从0开始编号。 ListIndex属性告诉哪个项目被选中。 未select时为-1。 如果您在下拉列表中列出工作表列的标题(当您初始化表单时可能会自动执行此操作),则用户select的标题(如“Joiners”)和ListIndex之间将存在直接关系。 MonthTable的第一列将有ListIndex 0.所以你可以通过加1将ListIndex转换成MonthTable的一列。