VBA Runtime Error 1004 while assigning formula to a cell

Copper Contributor

I have created a small macro to apply a currency conversion with a fixed factor on selected cells.

 

 

 

Sub ApplyUSD_ConversionRate()
'
' Devides through USD_ConversionRate on selected cells
'
    Dim cel As Range
    Dim selectedRange As Range

    Set selectedRange = Application.Selection

    For Each cel In selectedRange.Cells
        Debug.Print cel.Address, cel.Value, cel.HasFormula, cel.Formula
        If Not cel.HasFormula Then
            cel.Formula = "=" & cel.Value & "/USD_ConversionRate"
             >> VBA Runtime Error 1004 “Application-defined or Object-defined error”
        Else
            cel.Formula = "=(" & Right(cel.Formula, Len(cel.Formula) - 1) & ")/USD_ConversionRate"
        End If
    Next cel
End Sub

 

 

I figured out that I get a Runtime Error 1004 only if the cell contains decimals. 

 

Note: I have set the regional settings to German on my computer so the decimal character is comma!

 

Example:

In case of success: 

 

 

 

$T$3           65850        False         65850

 

 

In case of error: 

 

 

 

$T$2           218924,886839899           False         218924.886839899

 

 

 

Notice the difference in the number format of .Value and .Formula property of the cell. I suppose that this might be the reason of the Runtime error.

 

Btw, the code is in a module of the workbook.  

 

Any suggestions how I could avoid the Runtime error? 

 

2 Replies
In this case you could use cel.FormulaLocal instead of cel.Formula. That will ensure Excel does not take the comma in your decimal number to be a thousand separator (VBA speaks American)

Thanks, @Jan Karel Pieterse , for your suggestion. 

 

I could actually resolve the issue by using .Formula instead of .Value: 

 cel.Formula = "=" & cel.Formula & "/USD_ConversionRate"