繁体字和简体字之间进行转换,是编程中经常遇到的,虽然有很多在线工具可以实现转换,但是代码中如何能快速实现呢?其实利用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 LongPrivate Declare Function lStrLen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As String) As LongFunction Jian_Fan_Conv(ByVal strString As String, Optional ByVal iMode As Integer = 0) As StringDim lStrLength As LongDim strNew As StringConst J2F_MAPFLAG = &H4000000Const F2J_MAPFLAG = &H2000000Jian_Fan_Conv = ""lStrLength = lStrLen(strString)strNew = Space(lStrLength)If iMode = 0 ThenLCMapString &H804, J2F_MAPFLAG, strString, lStrLength, strNew, lStrLengthElseLCMapString &H804, F2J_MAPFLAG, strString, lStrLength, strNew, lStrLengthEnd IfJian_Fan_Conv = strNewEnd Function
代码是不是很简单,就是API函数LCMapString
实现转换。
参数dwMapFlags
用于控制转换方式,是简体转为繁体,还是繁体转为简体。参数iMode为转换模式,缺省值为0,实现简体转为繁体,如果为为0值,则繁体转为简体。注意:用于保存转换结果的字符串,需要先同空格填充为相应长度的字符串,否则API返回结果为空字符串。
使用下面的代码测试一下效果:
Sub Demo()Debug.Print "简体转繁体结果:" & Jian_Fan_Conv("唧唧复唧唧,木兰当户织")Debug.Print "繁体转简体结果:" & Jian_Fan_Conv("唧唧復唧唧,木蘭當戶織", 1)End Sub
立即窗口中的结果如下:
简体转繁体结果:唧唧復唧唧,木蘭當戶織繁体转简体结果:唧唧复唧唧,木兰当户织