MCP_infiltrator
MCP_infiltrator

Reputation: 4189

User Form - VLOOKUP and Form Calculation

I have a form with several fields. I have a field on the form where I would like a calculation to take place. This requires a VLOOKUP of a helper column function.

In a regular cell I can type the following:

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

Ins_Price_Tbl is a data table.

And get the answer I am looking for.

My form has the Text Boxes

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

I need txtAdjustmentCostYearA to perform the VLOOKUP where in this case C3 would just equal "Adjustment" or whatever text I type in and multiply it by the txtAdjustmentCountYearA.Value

So I would potentially have something like:

txtAdjustmentCountYearA.Value being equal to 2

txtAdjustmentYearA.Value being equal to 2018

txtAdjustmentCostYearA being equal to something like:

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

Upvotes: 0

Views: 70

Answers (1)

T.M.
T.M.

Reputation: 9948

As close as possible to your 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

Upvotes: 1

Related Questions