API实现快速转换简体字与繁体字

繁体字和简体字之间进行转换,是编程中经常遇到的,虽然有很多在线工具可以实现转换,但是代码中如何能快速实现呢?其实利用API可以快速实现繁体字与简体字直接的转换,函数代码如下。

Private Declare Function LCMapString Lib "kernel32" Alias "LCMapStringA" (ByVal Locale As Long, _
ByVal dwMapFlags As Long, ByVal lpSrcStr As String, ByVal cchSrc As Long, ByVal lpDestStr As String, ByVal cchDest As Long) As Long
Private Declare Function lStrLen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As String) As Long

Function Jian_Fan_Conv(ByVal strString As String, Optional ByVal iMode As Integer = 0) As String
    Dim lStrLength As Long
    Dim strNew As String
    Const J2F_MAPFLAG = &H4000000
    Const F2J_MAPFLAG = &H2000000
    Jian_Fan_Conv = ""
    lStrLength = lStrLen(strString)
    strNew = Space(lStrLength)
    If iMode = 0 Then
        LCMapString &H804, J2F_MAPFLAG, strString, lStrLength, strNew, lStrLength
    Else
        LCMapString &H804, F2J_MAPFLAG, strString, lStrLength, strNew, lStrLength
    End If
    Jian_Fan_Conv = strNew
End Function

代码是不是很简单,就是API函数LCMapString实现转换。

  • 参数dwMapFlags用于控制转换方式,是简体转为繁体,还是繁体转为简体。
  • 参数iMode为转换模式,缺省值为0,实现简体转为繁体,如果为为0值,则繁体转为简体。
  • 注意:用于保存转换结果的字符串,需要先同空格填充为相应长度的字符串,否则API返回结果为空字符串。

使用下面的代码测试一下效果:

Sub Demo()
    Debug.Print "简体转繁体结果:" & Jian_Fan_Conv("唧唧复唧唧,木兰当户织")
    Debug.Print "繁体转简体结果:" & Jian_Fan_Conv("唧唧復唧唧,木蘭當戶織", 1)
End Sub

立即窗口中的结果如下:

简体转繁体结果:唧唧復唧唧,木蘭當戶織
繁体转简体结果:唧唧复唧唧,木兰当户织

你可能感兴趣的:(VBA,API)