Compare number formatting of two cells in excel using vba - excel

My problem:
Cell A1: value =12 and the number property is general.
Cell A2: value =12 and the number property is number with 2 decimal points, so the number is shown as "12.00"
How can I validate if both cells have the same number property, either in VBA using macros or in any other way?

You can compare their NumberFormat property:
If Range("A1").NumberFormat = Range("A2").NumberFormat Then
However, There are a number of different formats, including custom formats, that can be applied to cells that would make them look the same, without them having exactly the same NumberFormat value.
This means that comparing formats will never be as reliable as comparing the values. (It is also unusual to need to compare formats.)

You can use the NumberFormat method.
Using this code, with 12 in A1 (formatted as general) and 12 in B1 (formatted as 12.00)
Option Explicit
Sub Stuff()
MsgBox Range("A1").NumberFormat
MsgBox Range("B1").NumberFormat
End Sub
Will return messages of "General" and "0.00" respectively.
So using
If Range("A1").NumberFormat = Range("B1").NumberFormat Then
-- do stuff here
End If
Will tell you if they are equal to one another or not.

It sounds like you are really concerned with the values of the cells. The .NumberFormat property simply masks how the value appears, visually, to the user of the spreadsheet.
So you can easily do an equivalence test on the two values, like:
Sub Test()
MsgBox [A1].Value = [A2].Value
End Sub
Or you could do this in the worksheet formula:
=A1=A2
That formula should return either True or False, and should ignore the cell's formatting.

Related

Is there a way to substitute a value in a formula using a UserForm?

I have a very long formula in columns I2:HM13 that contains values that need to change depending on what department uses the worksheet and these values may change over the course of the year. This formula repeats in all cells within the stated range with only the reference column/row changing. I would like to create a UserForm were the end user can input the values specific to their department in textboxes and click a commandbutton and the values in the textboxes get inserted into the formula.
I have tried some find and replace codes, but nothing I have tried has work at all. Below is the formula I am trying to modify.
=IF($H2="No","",IF(($B2-I$1)<100,"",IF(((($B2-I$1)*$C2)*1000000)<260000000000,"",IF(((I$1*$C2)*1000000)<330000000000,"",IF(AND(($B2-I$1)>=200,($B2-I$1)<=800,((($B2-I$1)*$C2)*1000000)>=620000000000,((($B2-I$1)*$C2)*1000000)<=920000000000,I$1>=375,I$1<=420,((I$1*$C2)*1000000)>=680000000000,((I$1*$C2)*1000000)<=790000000000,$C2>=1300,$C2<=2100),1)))))
The above is a small portion of the formula of interest. The values I am trying to changed based on the textbox inputs are all the values after the less than, less than or equal to, greater than, or greater than or equal to symbols.
For example in textbox 1 the user inputs 150, 150 would then replace all "100" in the formula. If the user inputs 270000000000 in textbox 2, all the "260000000000" would be replaced with 270000000000.
Your best approach would be to create sheet-scoped names which you then use in your formulas: your userform can then change the "refersto" values for those names to the user-supplied values.
Eg:
With ActiveSheet
.Names("FOO").RefersTo = txtName1.Value
.Names("BAR").RefersTo = txtName2.Value
End With
On your sheet:
=FOO/BAR
Found this solution to my question:
Private Sub CommandButton1_Click()
Dim cell As Range
For Each cell In Range("I2:HM2")
cell.Formula = Replace(cell.Formula, "100,", TextBox4.Value + ",")
cell.Formula = Replace(cell.Formula, "260000000000,", TextBox5.Value + ",")
Next cell
End Sub
I would need to repeat this format for all the values I would want to change per department.

If a cell is formatted as text, the formulas are not calculated

I need to keep the cells formatted as text and at the same time make sure that Excel calculates the formulas within them.
Is there a way to do it?
Embed your excel-formulas in the text-function.
=Text(your function,"#")
more info:
https://support.office.com/en-us/article/text-function-20d5ac4d-7b94-49fd-bb38-93d29371225c
edit: If your formulas are not being evaluated, then there can also be other causes for that than the cell-formatting.
I'm solved it!!!
In a Sheet module:
Option Explicit
Private Busy As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Busy Then
Busy = True
If ActiveSheet.ProtectContents Then ActiveSheet.Protect UserInterfaceOnly:=True
CalculateFormula Target.Row, Target.Column
Busy = False
End If
End Sub
In a standard module:
Option Explicit
Sub CalculateFormula(Row As Long, Column As Long)
Dim Format As String
If Left(Cells(Row, Column).Value, 1) = "=" Then
Format = Cells(Row, Column).NumberFormat
Cells(Row, Column).NumberFormat = "General"
On Error Resume Next
Cells(Row, Column).FormulaLocal = Cells(Row, Column).Value
On Error GoTo 0
Cells(Row, Column).NumberFormat = Format
End If
End Sub
It is unclear if you just need the format of the cell to be text, or if your need the results of a formula in a cell to be converted to a string/text. Excel formulas do no affect cell formatting, nor or are they affected by cell formatting. a perfect example of this is dates. Dates are really an integer counting the number of days since a start point. Day 1 is 1900/01/01 on a pc (On a mac I think its 1905/01/01 but could be wrong). If you enter today's date (2018/09/17) in any default cell, Excel identifies it as a date, changes the formatting of the cell and converts the date to 43360. You will see this if you change the cell format back to general and you will note that the number is right aligned. If you change the format of the cell to text, you will still see 43360 but instead it will be left aligned. More importantly its still a number and you can test it by using ISTEXT(A1) where A1 is the cell in question. It will still return true.
In order to make the contents of a cell a string, you can simply concatenate your formula with "".
=Your_Function&""
=1+1&""
Having said that. If a cell is formatted as a string, the FORMAT of the cell will remain a string despite whatever math calculation goes on inside it. So if you format A2 as text, and then place =1+1 inside it, the result in the cell will be the number 2 and the cell will be formatted as text.

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Hoping there is a way this can be done with a formula since I will be putting this on SharePoint as a shared workbook.
Column B contains Tasks, while Column E contains the Date and Time of when the Task was assigned. Is there a formula that would automatically enter the current date and time in Column E whenever someone entered data into column B?
Any assistance would be greatly appreciated.
Another way to do this is described below.
First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation. Then set maximum iterations to 1000.
The 1000 iterations doesn't matter for this formula, but it stops excel getting stuck in an infinite loop for other circular references.
After doing this, use the following formula.
=If(D55="","",IF(C55="",NOW(),C55))
Once anything is typed into cell D55 (for this example) then C55 populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.
This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.
This can be accomplished with a simple VBA function. Excel has support for a Worksheet Change Sub which can be programmed to put a date in a related column every time it fires.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
End If
End Sub
A quick explanation. The following "if" statement checks for two things: (1) if it is the second column that changed (Column B), and (2) if the cell 3 columns over (Column E) is currently empty.
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
If both conditions are true, then it puts the date into the cell in Column E with the NOW() function.
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
Range.Offset
Range.Column
Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.
open Excel
press "Alt+F11"
Double-click on the worksheet that you want to apply the change to (listed on the left)
copy/paste the code below
adjust the Range(:) input to correspond to the column you will update
adjust the Offset(0,_) input to correspond to the column where you would like the date displayed (in the version below I am making updates to column D and I want the date displayed in column F, hence the input entry of "2" for 2 columns over from column D)
hit save
repeat steps above if there are other worksheets in your workbook that need the same code
you may have to change the number format of the column displaying the date to "General" and increase the column's width if it is displaying "####" after you make an updated entry
Copy/Paste Code below:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date
End Sub
Good luck...
I'm afraid there is not such a function. You'll need a macro to acomplish this task.
You could do something like this in column E(remember to set custom format "dd/mm/yyyy hh:mm"):
=If(B1="";"";Now())
But it will change value everytime file opens.
You'll need save the value via macro.
You can use If function
Write in the cell where you want to input the date the following formula:
=IF(MODIFIED-CELLNUMBER<>"",IF(CELLNUMBER-WHERE-TO-INPUT-DATE="",NOW(),CELLNUMBER-WHERE-TO-INPUT-DATE),"")
Here is the solution that worked for me
=IF(H14<>"",NOW(),"")

How do I get the format of a cell in 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
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?
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.
I don't think there's any property of a cell that indicates whether the cell actually contains a numeric value, although VarType() might help, it gets tricky because Excel will allow a number-formatted cell to contain string, and a text formatted cell to contain numeric values, without overriding the NumberFormat property.
In any case you likely need some independent test to figure out whether a cell IsNumeric (or other criteria) AND whether its NumberFormat is among an enumerated list which you can define.
Sub numFormat()
Dim cl As Range
Dim numFormat As String
Dim isNumber As Boolean
For Each cl In Range("A1")
numFormat = cl.NumberFormat
isNumber = IsNumeric(Trim(cl.Value))
Select Case numFormat
Case "General", "0", "0.0", "0.00" ' <--- modify as needed to account for other formats, etc.
If isNumber Then
Debug.Print cl.Address & " formatted as " & numFormat
End If
Case Else
'ignore all other cases
End Select
Next
End Sub
I don't think the format of the cell is the important thing. Rather, it's the data type of the field in your database. If you have the string 'foobar' in a cell and you create an INSERT INTO sql statement that attempts to put that into a Long Integer field, it's going to fail regardless of tickmarks.
Conversely, if a cell contains a numeric value (like 100) that needs to go into a VARCHAR field, it will need tickmarks (like '100').
If you're using ADO, check the Type property of the Field object to determine the data type. Use this list http://support.microsoft.com/kb/193947 to see what the types are. Then set up the SQL statement according to the field type.

Format cell for comma-separated values

Written a VBA script which outputs numbers and I thought I had the correct format string for thousand-separating (4,656,565 5,343 232,434 etc) but its not working for certain magnitudes of numbers.
So far I am using Cells(x,y).NumberFormat = "#,###"
can someone provide me with the correct format string to thousand-comma-separate any number, no matter the magnitude?
This works for me. Notice, formatting the cell first before assigning the number to it
Option Explicit
Sub Sample()
With Cells(1, 1)
.NumberFormat = "#,##0"
.Value = 4.65656553432324E+16 '46565655343232400
End With
End Sub
RESULT
Cell A1 has 46,565,655,343,232,400

Resources