我一直在试图让这个代码适合我,但我已经碰壁了。我希望从文本框中获取vlookup命令,并在用户按下命令按钮时自动从多个组合框中选择匹配值。
这是我的逻辑。
Excel 2010> Userform> VBA
1)用户在文本框“TxtDXCode”中输入字母数字代码 2)用户按下按钮“CmdMap” 3)从该文本框中提取左3个字符并将它们分配给变量 4)使用所述变量填充文本框“TxtDxCodeLeft3”(这是一个冗余步骤,因此我有视觉确认代码工作)。 5)使用文本框“TxtDxCodeLeft3”的值作为vlookup命令的搜索参数。 6)使用vlookup从预先填充的组合框“CboCMChapter”和“CboCMCode”中选择一个列表项。
Private Sub CmdMap_Click()
'(((Extract left values from DX Code and Procedure Code strings to use in Vlookup.)))
'Define variables
Dim L1ResultDX As String
Dim L1ResultProc As String
Dim L2ResultProc As String
Dim L3ResultProc As String
'Assign values to variables
L1ResultDX = Left(TxtDxCode, 3)
L1ResultProc = Left(TxtProcCode, 1)
L2ResultProc = Left(TxtProcCode, 2)
L3ResultProc = Left(TxtProcCode, 3)
'Extract first 3 characters from DX Code for Vlookup command
Me.TxtDxCodeLeft3.Text = L1ResultDX
'Validate TxtDXCode
If TxtDxCode.TextLength < 6 Then
MsgBox "Missing or invalid code. ", vbExclamation, "DX Code Entry"
TxtDxCode.SetFocus
Exit Sub
End If
'(((Assign CM Codes & Chapters to comboboxes as result of Vlookup function.)))
'Set CM combobox default value based on Vlookup results
Me.CboCMChapter.Default = Application.VLookup(TxtDxCodeLeft3.Text, Worksheets("CM Chapters").Range("A3:B23,A26:A27,A29:A30"), 2, True)
Me.CboCMCode.Default = Application.VLookup(TxtDxCodeLeft3.Text, Worksheets("CM Codes").Range("A3:B283"), 2, True)
答案 0 :(得分:1)
为什么不尝试从TxtDxCodeLeft3中放入值并在excel单元格中调用它,然后从那里使用vlookup,然后将结果调用到userform。
range("A1").value = TxtDxCodeLeft3.value
cell A2 = vlookup(a1, range) - this will contain the lookup value for CboCMChapter
cell A3 = vlookup(a1, range) - this will contain the lookup value for CboCMCode
then call it again in the userform
CboCMChapter.value = range("a2").value
CboCMCode.value = range("a3").value
希望有所帮助
答案 1 :(得分:0)
我找到了答案。以下代码行格式错误。
'CM combobox default value based on Vlookup results
Me.CboCMChapter.Default = Application.VLookup(blah blah blah)
Me.CboCMCode.Default = Application.VLookup(blah blah blah)
正确的格式是:
'CM combobox default value based on Vlookup results
Me.CboCMChapter.Value = Application.WorksheetFunction.VLookup(blah blah blah)
Me.CboCMCode.Value = Application.WorksheetFunction.VLookup(blah blah blah)