Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

VBA Userform: Auto Calculate

0

My question is,

How do you auto calculate a text box in a userform that is auto-adding up the total amount of miles.  Any amount of miles I put in, I would like the total amount to auto calcuate that by 2.00   

to make it more dynamic, I would like the second amount to be 2.5

Example

 Address           1 = 10

total  Amount    =        $20.00

Answer
Discuss

Answers

0

I'm not sure how you want to determine when to use the second amount or not, but here is a basic code example of how to take a value from an input, multiply it by two, and put it into a label.

Label1.Caption = TextBox1.Text * 2

Label1 is the name of the label where the value will appear.

TextBox1 is the name of the input where the user will type the number.

You could replace the 2 with a variable and use an IF statement to determine when to use 2 or 2.5.

You can run this with the click of a button, just double-click the desired button on the form and paste the code into the active section of the window that will appear.

You could also just store the total amount in another variable or output it to the spreadsheet. You really weren't very clear on how you wanted this to work...

Discuss
0

If you want the value of the textbox to change automatically you need to use an event procedure. I suggest to use the BeforeUpdate event which occurs when the text box loses the focus, meaning when you move the cursor to any other control. You might consider using the Change event but that occurs whenever you enter a single character and i think you want the user to finish typing before you change what he enters.

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    Dim Tmp As Variant
    
    With TextBox1
        Tmp = Val(.Value)
        .Value = Format(Tmp * 2, "$0.00")
    End With
End Sub

The above example requires a text box by the anme of TextBox1. If your text box has another name please change both the name of the procedure and the name of the text box in the code. Install the procedure in the UserForm's code sheet. Make sure that application events are enabled - that's the default when you start Excel.

Of course, you could read the multiplier from another control where the user can change it between 2 and 2.5 for example. You can also direct the output to another text box, not the same in which the user made an entry.

Discuss


Answer the Question

You must create an account to use the forum. Create an Account or Login