Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

excel - Change region format to another language with VBA

I need to change the region format to "French (Canada)" in order for datevalue to accept french months (eg. 05 Mars, 12 Avril, etc) and then revert it back to "English (Canada)" within the VBA code.

I hope it's not as complex and that there is a write property that can modify this setting with VBA.

So far, I've found Application.International(xlCountrySetting) but it is only a read property.

This is the setting in question I wish to change:enter image description here enter image description here

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As pointed out in the comments, you can do this with a couple simple Windows API calls. Instead of assuming that the machine is currently set to "English (Canada)", I'd suggest testing the current setting with GetUserDefaultLCID, and then setting it back to that when you're done.

#If VBA7 Then
    Private Declare PtrSafe Function SetThreadLocale Lib "kernel32" _
        (ByVal Locale As Long) As Boolean
    Private Declare PtrSafe Function GetUserDefaultLCID Lib "kernel32" () As Long
    Private Declare PtrSafe Function LocaleNameToLCID Lib "kernel32" _
        (ByVal lpName As LongPtr, dwFlags As Long) As Long
#Else
    Private Declare Function SetThreadLocale Lib "kernel32" (ByVal Locale As Long) As Boolean
    Private Declare Function GetUserDefaultLCID Lib "kernel32" () As Long
    Private Declare Function LocaleNameToLCID Lib "kernel32" _
       (ByVal lpName As LongPtr, dwFlags As Long) As Long
#End If

Private Sub Test()
    'Get the locale identifier for French (Canada)
    Dim frCa As Long
    frCa = LocaleNameToLCID(StrPtr("fr-CA"), 0)
    'Make sure there function succeeded.
    If result = 0 Then
        'Cache the current locale
        Dim userLocale As Long
        userLocale = GetUserDefaultLCID
        'Switch to French (Canada)
        If SetThreadLocale(frCa) Then
            'en fran?ais
            '...
            'switch back
            SetThreadLocale userLocale
        End If
    End If
End Sub

Documentation links for the relevant functions are below:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...