VBA (Conditional Formatting) working code in Excel 2003, does not work in Excel 2020

回眸只為那壹抹淺笑 提交于 2020-08-10 18:58:05

问题


Basic code for applying a conditional format to a range, when range.value is lower than 7,2 it stays white, when higher than 8,1 it turns red. This code runs just fine in my Excel 2003 Macro-Enabled Workbook document, but when I have my brother open it in his work computer with Excel 2020, It throws this error

Run-time error '5': Invalid procedure call or argument

Private Sub totalEPS(mySelection As Range)
    With mySelection.FormatConditions
        .Delete
        With .Add(Type:=xlCellValue, Operator:=xlGreaterEqual, Formula1:="=7,2")
            .Interior.Color = 65535
            .StopIfTrue = False
        End With
        With .Add(Type:=xlCellValue, Operator:=xlGreater, Formula1:="=8,1")
            .Interior.Color = 255
            .StopIfTrue = False
        End With
    End With
End Sub

When he hits Debug it stops in the line

        With .Add(Type:=xlCellValue, Operator:=xlGreaterEqual, Formula1:="=7,2")

I cannot debug it because it does not throw any error in my computer, only on his.

The code uses the method over 50 times, it runs just fine 50 times in my laptop, and crashes in the first run on his. I honestly don't know what's wrong.


回答1:


I suspect it has to do with the decimal separator - that comma would be a dot on an en-US operating system.

Try adding this function to your module:

Public Function LocalizeDecimal(ByVal value As Double) As String
    LocalizeDecimal = Replace(Str(value), ".", Application.International(xlDecimalSeparator))
End Function

Then edit the Formula1 argument to something like this:

With .Add(Type:=xlCellValue, Operator:=xlGreaterEqual, Formula1:="=" & LocalizeDecimal(7.2))

And:

With .Add(Type:=xlCellValue, Operator:=xlGreater, Formula1:="=" & LocalizeDecimal(8.1))


来源:https://stackoverflow.com/questions/59994084/vba-conditional-formatting-working-code-in-excel-2003-does-not-work-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!