简体   繁体   中英

Format a cell as arbitrary currency regardless of locale, using VBA

This is really bugging me as it seems pretty illogical the way it's working.

I have a macro to format a cell as a currency using a bit of code to obtain the currency symbol.

Here is the code involved:

Dim sym As String
sym = reportConstants(ISOcode)
    'Just use the ISO code if there isn't a symbol available
    If sym = "" Then
    sym = ISOcode
    End If
With range(.Offset(0, 3), .Offset(3, 3))
.NumberFormat = sym & "#,##0;(" & sym & "#,##0)"
Debug.Print sym & "#,##0;(" & sym & "#,##0)"
End With

reportConstants is a dictionary object with currency symbols defined as strings. Eg reportConstants("USD") = "$" . This is defined earlier in the macro.

When the macro runs it gets the ISO code and should then format the cell with the corresponding currency symbol.

When I run it in one instance the ISO code is "USD" - so sym is defined as "$" - but it still formats the cell with a pound sign (£). When I debug.print the format cell string it shows $#,##0;($#,##0) so, as long as I got my syntax correct, it should use a dollar sign in the cell. But it uses a £ sign instead. (I am running a UK version of excel so it may be defaulting to £-sign, but why?)

Any help greatly appreciated.

I just recorded a macro to set the format to $xx.xx and it created this: [$$-409]#,##0.00 . Looks like the -409 localises the currency to a particular country; it works without it - try changing yours to .NumberFormat = "[$" & sym & "]#,##0.00"

Btw guess I read your question somewhat after posting ;) Excel is well influenced by the regional settings of your computer for currency, language, dates... Using numberformat can force it to keep the sign you require. if it is a matter of rounding up you can try to: On Excel 2010, go to File - Options - Advanced and scroll down to "When calculating this workbook" and click on the "set precision as displayed" and OK out.

Try this: given your values are numerics/ integers/decimals....

Range("a2").Style = "Currency"

Or you can use format:

Format(value, "Currency")

Format(Range(a2).value, "Currency")

References:

http://www.mrexcel.com/forum/excel-questions/439331-displaying-currency-based-regional-settings.html

http://www.addictivetips.com/microsoft-office/excel-2010-currency-values/

(PS: I am on mobile, you may try these two links)

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