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

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. E.g. 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)

Related

Setting Number Format to Accounting in VBA

With ActiveSheet
.Range("T26:T31").NumberFormat = "_(£* #,##0.00_);_(£* (#,##0.00);_(£* " - "??_);_(#_)"
I am trying to set the format of a cell range to Accounting, I have looked at the number format (above) and tried setting it to that, but I get a Type Mismatch.
I also tried doing Debug.Print Application.ActiveCell.NumberFormatLocal to find out how excel reads it, copied that in and still with no luck.
Anyone got any ideas?
You need to double any quotation marks inside the format code, so:
.Range("T26:T31").NumberFormat = "_(£* #,##0.00_);_(£* (#,##0.00);_(£* "" - ""??_);_(#_)"

Excel TEXT(dd.mm.yyyy) function and different client languages

How can I make a function with a formatted date that will work in every language? I want to make the following function:
=CONCATENATE(TEXT(C8;"TT.MM.JJJJ");"/";G8)
The problem here is, that I use the english client but because I'm a german, excel forces me to use T for day and J for year. I think this will cause problem on a PC located in england (for example).
I think [$-409] won't work because I still have to use T for day and J for year. Is there a good solution for this (function wise)?
If you pass the value of a formula in "" then it cannot be changed based on the localisation settings.
A good way to do it is to use a custom function with VBA, returning "TT.MM.JJJJ" if you are in Germany and "DD.MM.YYYY" if you are in England.
Public Function CorrectString() As String
Select Case Application.International(XlApplicationInternational.xlCountryCode)
Case 1
CorrectString = "DD.MM.YYYY"
Case 49
CorrectString = "TT.MM.JJJJ"
Case Else
CorrectString = "ERROR"
End Select
End Function
Would allow you to call the function like this:
=CONCATENATE(TEXT(C8;CorrectString());"/";G8)
And depending on the excel language, it would give either the German or the English versions.
To simplify the formula, try calling only:
=TEXT(21322;CorrectString())
This should return 17.05.1958.
Source for the regional languages, mentioned by #Dan at the comments:
https://bettersolutions.com/vba/macros/region-language.htm
Or run this to see the corresponding number of your current Excel:
MsgBox xlApplicationInternational.xlCountryCode
Just dropping in another imho elegant (VBA free) alternative taken from: Stackoverflow answer by #Taosique
=IF(TEXT(1,"mmmm")="January",[some logic for English system],[some logic for non-English system])
I've had the same problem and solved it with similar VBA Function. My function accepts input in international format, and outputs the local version for user.
Please see code below:
Function DateFormater(sFI As String)
Dim aFI() As String
aFI = split(StrConv(sFI, vbUnicode), Chr$(0))
ReDim Preserve aFI(UBound(aFI) - 1)
For i = 0 To UBound(aFI)
Select Case (aFI(i))
Case "m", "M"
DateFormater = DateFormater & Application.International(xlMonthCode)
Case "y", "Y"
DateFormater = DateFormater & Application.International(xlYearCode)
Case "d", "D"
DateFormater = DateFormater & Application.International(xlDayCode)
Case Else
DateFormater = DateFormater & aFI(i)
End Select
Next i
End Function
A simpler solution is to use generic Excel functions.
=CONCATENATE(TEXT(DAY(C8;"00");".";TEXT(MONTH(C8);"00");".";YEAR(C8);"/";G8)

Excel VBA extract date from CSV txt

I'm having trouble extracting this text, exactly as it appears, from a CSV. There are similar questions posted on SO but they don't match my requirements:
I want to extract "31 January 2017" from this row:
4,'31 January 2017','Funds Received/Credits',56,,401.45,
Currently, VBA considers it "31 Jan" without the year. I've tried applying .NumberFormat to the cell (general, text, date).
SOLUTION REQUIREMENTS:
No user action required -- Interact with the file only using VBA (not using File > Import > Wizard)
Compatible with VBA Excel 2003
Extract the full text regardless of Excel or operating system date settings
Thank you for your ideas
You can use the split function, using the comma as a delimiter like this:
sResult = Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1)
If you dont want the single quotes, then add the replace function like this:
sResult = Replace(Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1), "'", "")
If you include the "Microsoft VBScript Regular Expressions 5.5" Reference, you can set up a pattern that will extract the whole date if it is found. For example:
Dim tstring As String
Dim myregexp As RegExp
Dim StrMatch As Object
tstring = 'Line from the CSV, or entire CSV as one string
Set myregexp = New RegExp
myregexp.Pattern = "\d{1,2} [A-Z]{3,9} \d{4}"
Set StrMatch = myregexp.Execute(tstring)
You get the benefit from this method that all the dates in the CSV will be pulled out at once, much faster than using a split line by line. Additionally, the dates may be accessed by using
DateStr = StrMatch.Item(index)
for the whole string line, or substrings can be set up to get specific parts of the string(Such as month, day, year).
myregexp.Pattern = "\(d{1,2}) ([A-Z]{3,9}) (\d{4})"
Set StrMatch = myregexp.Execute(tstring)
DateStr = StrMatch.Item(index1).SubMatches(index2)
It is a very powerful tool, with a simple set of symbols for development of patterns. I highly suggest you familiarize yourself with it for manipulation of large strings.

VBA dots from database get loaded into textbox as comma

I know the Headline sounds odd so I will start off with a screenshot:
As you can see, the problem is that the point suddenly changes to a comma when I look up an ID in the UserForm.
Before recalling Infos, I am saving all Information rather straightforward:
with ws
Range("BH" & lastRow).value = Me.payinfoOnTime
Range("BI" & lastRow).value = Me.payinfo30
Range("BJ" & lastRow).value = Me.payinfo60
Range("BK" & lastRow).value = Me.payinfo90
Range("BL" & lastRow).value = Me.payinfo90more
End with
Recalling the respective info for a searched ID is done by:
Set FoundRange = ws.Range("D4:D500").Find(What:=Me.SearchSuppNo, LookIn:=xlValues)
With ws
Me.SEpayinfoontime = FoundRange.Offset(0, 56)
Me.SEpayinfo30 = FoundRange.Offset(0, 57)
Me.SEpayinfo60 = FoundRange.Offset(0, 58)
Me.SEpayinfo90 = FoundRange.Offset(0, 59)
Me.SEpayinfo90more = FoundRange.Offset(0, 60)
end with
The Problem is that later calculations for scores are depending on those textboxes and I constantly get an error, unless I always manually change the commas back to points.
Any ideas how I can fix this?
The line:
Me.SEpayinfoontime = FoundRange.Offset(0, 56)
is in fact:
Me.SEpayinfoontime.Value = FoundRange.Offset(0, 56).Value
When you populate an MSForms.TextBox using the .Value property (typed As Variant), like you implicitly do, and providing a number on the right side, the compiler passes the value to the TextBox as a number, and then the value is automatically converted to string inside the TextBox.
Exactly how that conversion happens does not appear to be documented, and from experiment, it would appear there is a problem with it.
When you freshly start Excel, it would appear assigning .Value will convert the number using the en-us locale, even if your system locale is different. But as soon as you go to the Control Panel and change your current locale to something else, .Value begins to respect the system locale, and changes its result depending on what is currently selected.
It should not be happening and I would see it as an Excel bug.
But if you instead assign the .Text property, the number is converted to string using the current system decimal dot, and that conversion happens outside of the TextBox, because the compiler knows .Text is a string, so it converts the right-hand side number to string beforehand.
So in your situation I would:
Make sure I always use the .Text property explicitly:
Me.SEpayinfoontime.Text = ...
Make sure I explicitly use the correct kind of functions to convert between text and numbers:
Me.SEpayinfoontime.Text = CStr(FoundRange.Offset(0, 56).Value)
MsgBox CInt(Me.SEpayinfoontime.Text) / 10
although this step is optional and represents my personal preference. Given that it's a string on the left side of the assignment, VB will use CStr automatically.
Go to Excel's settings to make sure the "Use system separators" tick is set.
Check what locale is selected in the Control Panel - Language and Regional settings.
If it is not En-Us, I would select En-Us to make sure the decimal separator is a dot there.
Restart Excel.

VBA: Get current month in russian language

I`m trying to get current month while my system language changed to "Russia",it gives "??????".
Code:
Dim presDate as String
presDate = Format(Date,"ddmmmmyyyy")
my above code gives output as "??????".I`m using Excel 2010.
Please suggest an answer.
Cyrillic letters should be displayed properly in VBE Editor, including debug window, if you change Language for non-Unicode programs to Russian in Control Panel - Regional and Language Options.
This code works. It would be called as '=mydate(date_value)', where date_value can be a reference to a cell with a date in it, a string value such as '"11/2/96"', an Excel function that returns the system's current date (e.g., '=mydate(TODAY())' or '=mydate(NOW()).
Option Explicit
Function mydate(cel As Variant) As String
If (TypeName(cel) = "Range") Then
mydate = Format(cel.Value, "mmmm dd yyyy")
ElseIf TypeName(cel) = "String" Then
mydate = Format(datevalue(cel), "mmmm dd yyyy")
ElseIf TypeName(cel) = "Double" Then
mydate = Format(Round(cel, 0), "mmmm dd yyyy")
Else
mydate = CVErr(xlErrValue)
End If
End Function
When I do this in the immediate window
Debug.Print Format(now,"ddmmmmyyyy")
in the immediate window I get
26???????2013
and when I do
cells(1,1)=Format(now,"ddmmmmyyyy")
in cell A1 I get
26февраля2013
I think the VBA IDE just can not do non-latin characters (probably limited to ASCII).

Resources