Multiple language date formats in Excel with VBA - excel

I'm trying to have the current date recognized in Excel using an =TEXT(TODAY(),"mmmm d yyyy") function, but I have run into issues with Canadian users based in Quebec, who may have a system install set to English or French, and likewise an Office install in one language or the other. For today's date, my spreadsheet pulls March 10 2021 on my computer, but the result has been askew for each Quebec-based user I have tested with.
In order to resolve this, I set up a VBA function to pull the application's language setting, with the intention to use a simple IF to check the language code and change from "mmmm d yyyy" to "mmmm j aaaa" (the letters to match the French journée for day and année for year, as per consulting the formats available on French Excel's TEXTE function). My function worked... but the output has come back incorrect each time.
Public Function LangCheck()
Dim lang_code As Long
lang_code = Application.LanguageSettings.LanguageID(msoLanguageIDUI)
LangCheck = lang_code
End Function
So that did its job, but the outputs should have been March 10 2021 or mars 10 2021. Instead from two different users I have received:
March j Wednesday, from a user with a French Excel setting, confirmed by the code outputting language ID 1036.
mars d yyyy, from a user with an English Excel setting on a French OS, confirmed by the code outputting language ID 1033.
Excel is translating every function to its French cognate, but won't translate the formats for the TEXT function on its own. Does anyone have a suggestion for a VBA or function-based solve to this conundrum so that I can ensure consistent dates return regardless of language?

You can use the Application.International properties to extract the correct DMY tokens, and use a named reference for the text function format code:
Change your formula to:
=TEXT(TODAY(),"dtFormat")
And store the below code into the ThisWorkbook module
Wherever the file is opened, the Sub will run and ensure that the dtFormat name has the appropriate DMY codes for the locale.
Option Explicit
'change text function date code
Private Sub Workbook_Open()
Dim yrCode As String, mnthCode As String, dyCode As String
Dim dtCode As String
Dim nM As Name
With Application
yrCode = WorksheetFunction.Rept(.International(xlYearCode), 4)
mnthCode = WorksheetFunction.Rept(.International(xlMonthCode), 4)
dyCode = WorksheetFunction.Rept(.International(xlDayCode), 1)
End With
'Can only add a name if it is absent
For Each nM In ThisWorkbook.Names
If nM.Name = "dtFormat" Then
nM.Delete
Exit For
End If
Next nM
dtCode = mnthCode & " " & dyCode & " " & yrCode
ThisWorkbook.Names.Add _
Name:="dtFormat", _
RefersTo:="=""" & dtCode & """", _
Visible:=False
End Sub

Related

Is there a way to use another language for date symbols when calling the format function in vba?

Another program sends a date format in the computer's local language to excel, i.e ÅÅÅÅ-MM-DD
VBA can't interpret this because the Format function only supports date symbols in English.
I can only retrieve localized date symbols from the local language, like ÅÅÅÅ-MM-DD. the format function only accept English localized date symbols YYYY-MM-DD. I need a function that can interpret date format in local system language or is able to translate ÅÅÅÅ-MM-DD with code to YYYY-MM-DD.
More examples:
DD.MM.ÅÅÅÅ to DD.MM.YYYY (local system language Swedish to English)
MM.DD.ÅÅÅÅ to MM.DD.YYYY (local system language Swedish to English)
JJ.MM.AAAA to DD.MM.YYYY (local system language French to English)
DD.MM.RRRR to DD.MM.YYYY (local system language Polish to English)
The workaround I've come up with uses TEXT formula to interpret the local system languages date format.
This *should* work with different local system languages:
Sub tstLocalDate()
Dim yrCode As String
Dim mnthCode As String
Dim dyCode As String
Dim dateFormat As String
yrCode = WorksheetFunction.Rept(Application.International(xlYearCode), 4)
mnthCode = WorksheetFunction.Rept(Application.International(xlMonthCode), 2)
dyCode = WorksheetFunction.Rept(Application.International(xlDayCode), 2)
dateFormat = yrCode & "-" & mnthCode & "-" & dyCode
Msgbox LocalDateFormat(DateValue(Now()), dateFormat)
End Sub
Function LocalDateFormat(inputDate As String, inputLocalFormat As String)
Dim LocalTextFormula As String
With ThisWorkbook.Sheets(Meta.Name).Range("A3")
.Formula = "=text("""",""?"")"
LocalTextFormula = Left(.FormulaLocal, InStr(1, .FormulaLocal, "("))
.FormulaLocal = LocalTextFormula & """" & inputDate & """;""" & inputLocalFormat & """)"
LocalDateFormat = .Value
End With
End Function
I've no idea how vulnerable this workaround is. If the text formula uses the systems local language to interpret date formats it should work for most cases, but if it's based on used excel language it won't work.
Is it possible to solve this without using excel formulas?
I guess you don't need all this.
Dim inputDate As String
Dim trueDate As Date
inputDate = "2021-12-31"
trueDate = DateValue(inputDate)
ThisWorkbook.Sheets(Meta.Name).Range("A2") = trueDate
Then apply the date format you prefer to the A2 range.

Convert date to string for automated directory searching

My ultimate goal is to be able to search a file path, where another user will be creating a new folder each month (for example next month the user will create the folder "January 2022"), and I need to be able to search for that folder in an automated way based on the current month and year.
My plan is to create a string object like so:
Dim strDirectory As String
strDirectory = "C:\foo\bar\baz\" & strCurrentMonthName & " " & strCurrentYear
But, I'm having trouble extracting the year as text. Originally I tried to do this:
Dim TestMonth As String
Dim TestYear As String
TestYear = Year(Now)
TestMonth = GetMonthName(Format(Now, "mm"))
Problem is that testYear gets returned as 7/13/1905. This webpage shows how to fix this error in a spreadsheet, but that's not going to help my situation as the date will never be pulled from a spreadsheet (as I feel that's a very error-prone way to do things). The Year function supposedly only works on Variant, Numeric, or String expressions and I don't know how to get just the year from Now.
Keep in mind that my ability to access standard libraries is very limited, I'm using an older version of Excel (2016) and have no control over packages or updates (there are certain features I've had to do without such as MonthName() for example, I had to create my own version of that)
Format returns a Variant (String) containing an expression formatted according to instructions contained in a format expression.
So whatever format you express in Format will be returned as a string.
Public Sub Test()
Dim CurrentDate As Date
CurrentDate = Date
Dim strDirectory As String
strDirectory = "C:\foo\bar\baz\" & Format(CurrentDate, "mmm yy") '"C:\foo\bar\baz\Dec 21"
strDirectory = "C:\foo\bar\baz\" & Format(CurrentDate, "mmmm yyyy") '"C:\foo\bar\baz\December 2021"
End Sub
No need for a GetMonthName function - Format(Now(),"mmmm") returns December this month.
Figured it out:
Dim TestMonth As String
Dim TestYear As Date
testYear = Now
TestMonth = GetMonthName(Format(Now, "mm"))
Range("A1").Select
ActiveCell.FormulaR1C1 = "C:\foo\bar\baz\" & TestMonth & " " & Year(TestYear)
Output:
C:\foo\bar\baz\December 2021

Date format excel in diferent systems German to English

I came across a problem, I try to export a date by using IF-function in excel als followed,
=WENN(C2="Y";TEXT(HEUTE();"JJJJMMTT");"")
it is in German, which in English is,
=IF(C2='Y'; TEXT(TODAY();"YYYYMMDD");'')
The language of My computer is in German, so it works well, but my colleagues in USA had problem, which they can't export the date with correct date, it shows today as example "JJJJ16TT", it can't show the year and day...
I don't know how to set it right. So I try to ask help from you.
Thanks and best regards.
Two possible methods:
Don't use the TEXT function.
Change your formula to:
=WENN(C2="Y";HEUTE();"")
- and apply a number format to the cell without the LCID.
Especially if your code is part of a longer function, you can
Use a Defined Name for the date string
Create a Workbooks_Open event to change that Name depending on the language of the user
Change your formula to: =WENN(C2="Y";TEXT(HEUTE();dtFormat);"")
eg:
To enter this Macro (Sub), <alt-F11> opens the Visual Basic Editor.
In the Project Explorer window, select ThisWorkbook under the relevant VBA Project.
Paste the code below into the window that opens.
Option Explicit
'change text function date code
Private Sub Workbook_Open()
Dim yrCode As String, mnthCode As String, dyCode As String
Dim dtCode As String
Dim nM As Name
With Application
yrCode = WorksheetFunction.Rept(.International(xlYearCode), 4)
mnthCode = WorksheetFunction.Rept(.International(xlMonthCode), 2)
dyCode = WorksheetFunction.Rept(.International(xlDayCode), 2)
End With
'Can only add a name if it is absent
For Each nM In ThisWorkbook.Names
If nM.Name = "dtFormat" Then
nM.Delete
Exit For
End If
Next nM
dtCode = yrCode & mnthCode & dyCode
ThisWorkbook.Names.Add _
Name:="dtFormat", _
RefersTo:="=""" & dtCode & """", _
Visible:=False
End Sub

Macro works on every computer except one where it gives "1004 error"

Disclaimer: I've read the relevant questions/answers regarding Error 1004 and I couldn't find a solution.
I have a macro that I distributed within the team and it works perfectly on all computers (including mine) except one. She's running the same version of Excel on the same system and she can use other macros except this one, I get the "Error 1004 SaveAs function failed" message. It is by a very long shot but did I miss some security setting or is there some problem with the code that could cause this? This is the code in question:
Sub PSSaveFile()
Dim myVal2 As Variant
Dim myValn2 As String
Dim myDate As String
Dim mFilePath As String
myVal2 = InputBox("Please enter today's date in mm-dd format")
myValn2 = Replace(myVal2, "-", "\")
myDate = Date
mFilePath = "\\xxxxxxxx003\xxx_emea\TCU_REPORTS\APPS\Reports\Regional\xxxxx for PC Web xx\2017\" & myValn2
ActiveWorkbook.SaveAs FileName:=mFilePath & "\xxxRHLogs-" & myDate & "_checked"
End Sub
Let me guess - the guy with the other computer is from another country, thus using his own regional settings on the PC. Thus the date format is a bit fancier, e.g. dd/mm/yyyy and it is not allowed to save it as a file because of this.
Try to change the date like this:
myDate = year(date) & month(date) & day(date)
and try again. This would eliminate the fancy settings part.

Generate workbook unique ID from template in Excel

In my organization we have an Excel template that all employees have to fill frequently. This template originates hundreds/thousands of Excel files (workbooks) per year.
For the sake of organisation, I urgently need to have a unique ID for each of these files (i.e. unique ID per workbook generated by this template).
Currently, my idea is to generate the following ID in a cell of the workbook:
[user]-[YYYYMMDD]-[hhmmss]
in which:
user is a string representing the username of the employee which would be filled in by the user. So no problem here.
YYYYMMDD is year, month and day
concatenated
hhmmss is hour, minute and second concatenated
For this effect, I would need that my Excel template automatically fills a cell with the YYYYMMDD-hhmmss information with the exact date and time of generation.
This information should be created once the template generates the workbook, and cannot be changed ever after. So these should be values in a (protected) cell and not a formula (I guess).
I cannot figure out how to do this after searching for a long time. I am not sure if it is needed or not, but I am no master of VBA.
The idea of having a date/time field is good .... create a workbook smilar to this
add the following code to the ThisWorkbook module:
Private Sub Workbook_Open()
If [B2] = "" Then
' timestamp
[B2] = Now()
' suppress warning when saving macro containing workbook in non-macro format
Application.DisplayAlerts = False
' save under calculated name
ActiveWorkbook.SaveAs [B1] & "-" & Format([B2], "YYYYMMDD-hhmmss")
' turn on alerts again
Application.DisplayAlerts = True
End If
End Sub
and save as a macro enabled template
Then create a [File - New] from this template .... it will immediately be saved under the name of the user with macros removed so that the code can't hit it another time.
The user name could be retrived from the environment or from the registry.
Alternatively you can examine if the file has a true name or (still) is named Book nnn which means it hasn't been saved before; this removes the need to reserve a timestamp cell in your workbook
Here are a couple of functions you could use to get your id. If you put this inside a vba module on your template you will be able to call the functions from the worksheets or other vba code (e.g. in workbook just enter '=get_id()', in vba you would do something like 'id = get_id()' to call this:
Option Explicit
Public Function lpad(string1, padded_length, _
Optional pad_string = " ")
Dim chars
chars = padded_length - Len(string1)
lpad = WorksheetFunction.Rept(pad_string, chars) & string1
End Function
Public Function get_id()
Dim user
Dim YYYYMMDD
Dim hhmmss
user = Environ("username")
YYYYMMDD = Year(Now()) & lpad(Month(Now()), 2, 0) & lpad(Day(Now()), 2, 0)
hhmmss = lpad(Hour(Now()), 2, 0) & lpad(Minute(Now()), 2, 0) & lpad(Second(Now()), 2, 0)
get_id = user & "-" & YYYYMMDD & "-" & hhmmss
End Function
The lpad function is just for formatting (so that you get 07 for July instead of 7 etc.). I have also added something here to set the user to the windows environment variable for the current user's name, but if you want to promt the user instead this part could easily be replaced.
Let me know if you have any questions.

Resources