简体   繁体   中英

Formatting Currencies based on a table with VBA

So I want to apply number formatting to the value in the cells in column "AC" based on the currency denoted in column "O" by doing a vlookup on a named range I have on a different sheet (named "currencies")

Here is the code in question that is throwing up errors about being "unable to get the VLookup Property of the WorksheetFunction class"

If Not (Range("O" & i)) = vbNullString Then
    If Not IsEmpty(Range("O" & i)) Then
        Range("AC" & i).NumberFormat = 
        Application.WorksheetFunction.VLookup(Range("O" & i), currencies, 2, False)
    End If
End If

and here is the table that comprises the named range "currencies"

在此处输入图片说明

Anyone have any suggestions for why this isn't working and ways I can make it more resilient to throwing up errors that the people who will actually be using this macro wont understand?

Here I would use the evaluate function, because it facilitates writing more complex formulas in vba. Now because of the IFERROR there will be no error just a blank cell if the formula does not work. Once a value is retrieved by the evaluate function, then apply your formatting.

If Not (Range("O" & i)) = vbNullString Then
    If Not IsEmpty(Range("O" & i)) Then
        If Evaluate("IFERROR(VLOOKUP(O" & i & ",currencies, 2, False),"""")") <> "" then
          'APPLY NUMBER FORMATTING HERE
           Range("AC" & i).Numberformat = ""
        End if
    End If
End If

Based on previous questions you have asked, I imagine your code should look like this:

If Not (Range("O" & i)) = vbNullString Then
    If Not IsEmpty(Range("O" & i)) Then
        If Evaluate("IFERROR(VLOOKUP(O" & i & ",currencies, 2, False),"""")") <> "" then
          'APPLY NUMBER FORMATTING HERE
           Select Case ("IFERROR(VLOOKUP(O" & i & ",currencies, 2, False),"""")")
           Case "USD"
           Range("AC" & i).NumberFormat = "$#,##0.00_);($#,##0.00)"
           Case "RMB"
           Range("AC" & i).NumberFormat = "[$¥-zh-CN]#,##0.00;[$¥-zh-CN]-#,##0.00"
           Case "EUR"
           Range("AC" & i).NumberFormat = "[$€-x-euro2] #,##0.00_);([$€-x-euro2] #,##0.00)"
           Case "GBP"
           Range("AC" & i).NumberFormat = "[$£-en-GB]#,##0.00;-[$£-en-GB]#,##0.00"
           Case "HKD"
           Range("AC" & i).NumberFormat = "[$HK$-zh-HK]#,##0.00_);([$HK$-zh-HK]#,##0.00)"
           Case "JPY"
           Range("AC" & i).NumberFormat = "[$¥-ja-JP]#,##0.00;-[$¥-ja-JP]#,##0.00"
           End Select
        End if
    End If
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM