Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Userforms. Textbox as number value to cell

Tags:

excel

vba

I've been searching for a solution to this for a while and have been unsuccessful in finding. Essentially, I have the user of my document populating fields in a user form that my code then puts into the appropriate cells. One of these input fields is a number but, no matter how I instruct excel to format the cell, it still is text in the end and I can't perform any calculations. I'm sure this is probably a pretty simple fix but I've been unsuccessful so far in finding a solution. As always, any help is appreciated!

thanks!

like image 608
ye-olde-dev Avatar asked Apr 03 '14 15:04

ye-olde-dev


People also ask

How do I link a textbox to a cell in Excel VBA?

To link a text box to a cell, first (1) select the text box and then in the formula bar, (2) type the equal (=) symbol and (3) click on the cell you want to link. When done, press Enter.

How do I set the value of a textbox in VBA?

Answer: To set the value of Textbox2 based on the value entered in Textbox1, you need to place your VBA code on the "After Update" event of Textbox1. To do this, open your form in Design View. Under the View menu, select Properties. Highlight the textbox called Textbox1.


1 Answers

You need to convert the value from text to a numeric type before putting it into a cell.

Assuming your textbox is called txtNumber and you're outputting to cell Output!A1, the code would be:

Sheets("Output").Range("A1") = CDbl(txtNumber)

Other conversion functions you might want to use are CLng (convert to Long), CInt (convert to Integer), CDec (convert to decimal, useful for currency values).

This code will raise an error if the user types a non-numeric text value into the field. You should validate on the textbox's Change event and disable the OK button if invalid data is inputted.

like image 116
Tmdean Avatar answered Nov 02 '22 04:11

Tmdean