Excel VBA用户表单-VLOOKUP和表单计算

时间:2018-12-09 17:49:00

标签: excel vba excel-vba userform

我有一个包含多个字段的表格。我在表格上有一个要进行计算的字段。这需要VLOOKUP个辅助列函数。

在常规单元格中,我可以输入以下内容:

=VLOOKUP(B3&C3&D3,Ins_Price_Tbl,5,0)

Ins_Price_Tbl是数据表。

得到我要找的答案。

我的表单具有文本框

txtAdjustmentCountYearA - An integer
txtInsurance - A String
txtAdjustmentYearA - A year like 2018
txtAdjustmentCostYearA - The result field

我需要txtAdjustmentCostYearA来执行VLOOKUP,在这种情况下,C3等于“调整”或我输入的任何文本,然后乘以txtAdjustmentCountYearA.Value

所以我可能会有类似的东西:

txtAdjustmentCountYearA.Value等于2

txtAdjustmentYearA.Value等于2018

txtAdjustmentCostYearA等于:

=VLOOKUP(Me.txtInsurance.Value&"Whatever I type in here"&Me.txtAdjustmentYearA,Ins_Price_Tbl,5,0) * txtAdjustmentCountYearA.Value

1 个答案:

答案 0 :(得分:1)

尽可能靠近您的OP

Option Explicit                             ' declaration head of code module

Private Sub CommandButton1_Click()
Dim ws As Worksheet                         ' provide for range reference
Set ws = ThisWorkbook.Worksheets("MySheet") ' <~~ change to your sheet name
Dim searched As String, found As Variant, factor As Double
searched = Me.txtInsurance.Text & ws.Range("C3").value & Me.txtAdjustmentYearA.Text
' use the Application function VLookup instead of worksheetfunction.VLookup
' allowing to ask a IsError condition (variable found has to be of type Variant!)
  found = Application.VLookup(searched, ws.Range("Ins_Price_Tbl"), 5, 0)
' Textbox values are always strings and have to be converted (e.g. to Double)
  If IsNumeric(txtAdjustmentCountYearA.Text) Then factor = CDbl(txtAdjustmentCountYearA.Text)
' Check possible errors before assigning result to textbox (again as String!)
  If Not IsNumeric(found) Or IsError(found) Then
     Me.txtAdjustmentCostYearA.Text = "Nothing found"
  Else
     Me.txtAdjustmentCostYearA.Text = found * factor
  End If
End Sub