Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the format of a cell in VBA

Tags:

excel

vba

When iterating through cells in a worksheet, how can I get what the format setting on the cell is? Because based on this, I would like to build a SQL statement to either add the single ticks or not to the value retreived

like image 548
Fat Owl Avatar asked Sep 15 '25 03:09

Fat Owl


2 Answers

Sounds like you need the VarType() function. Vartype(Range("A1"))


OK, so you don't want to know the format setting for the cell, but whether the value is numeric. Can you just call IsNumeric(Range("A1")) and quote it if False?


Based on your comment that some numbers are stored as text in the DB, you are not going to solve this by a simple formula. Can't you just quote the values as you build your SQL statement?

like image 118
nunzabar Avatar answered Sep 16 '25 18:09

nunzabar


Try using the following in VBA:

Range("A1").NumberFormat = "0.00" 'Sets cell formatting to numeric with 2 decimals.
Range("A1").Formula = "=Text(6, " & """0.00""" & ")" 'Looks like a number _
                                                     ' but is really text.
Debug.Print WorksheetFunction.IsNumber(Range("A1")) 'Prints False

Range("A1").Value = 6 'Puts number into the cell, which also looks like 6.00

Debug.Print WorksheetFunction.IsNumber(Range("A1")) 'Prints True

This should tell you if the value is really text or really a number, regardless of the cell's formatting properties.

The key is that the intrinsic Excel IsNumber() function works better for this purpose than the VBA function IsNumeric. IsNumber() tells you whether the cell's value is a number, whereas IsNumeric only tells you if the cell is formatted for numeric values.

like image 38
Joe Brooks Avatar answered Sep 16 '25 16:09

Joe Brooks