Private Function StrToHex(ByVal s As String) As String Dim buff() As Byte Dim result As String Dim tmps As String '先将字串转换为byte数组,一个中文字符占两个字节,一个英文字符占一个字节 buff = StrConv(s, vbFromUnicode) Dim i As Long For i = 0 To UBound(buff) '将各个字节转化为hex字串(每个字节两个字符,不足的前面补0) tmps = Right("00" + Hex(buff(i)), 2) '连接各个hex字串 result = result + tmps Next StrToHex = result End FunctionPrivate Sub Command1_Click() '测试 Dim s As String s = "这是一个test" Dim s1 As String s1 = StrToHex(s) MsgBox s1 End Su
Function StrToHex(xStr As String) As String Dim i As Long, tmp() As Byte: tmp = xStr For i = 0 To UBound(tmp) StrToHex = StrToHex & Format(Hex(tmp(i)), "0#") Next End FunctionFunction HexToStr(xHex As String) As String Dim i As Long, tmp() As Byte ReDim tmp(Len(xHex) / 2) As Byte For i = 0 To UBound(tmp) tmp(i) = Val("&H" & Mid(xHex, i * 2 + 1, 2)) Next HexToStr = tmp End FunctionPrivate Sub Form_Load() Debug.Print StrToHex("字符串转16进制") Debug.Print HexToStr("575B267B324E6C8F31003600DB8F3652") End Sub
哦,如果字母想做一个字节算,就改成这样Function StrToHex(xStr As String) As String Dim i As Long, tmp() As Byte: tmp = xStr For i = 0 To UBound(tmp) If tmp(i) Then StrToHex = StrToHex & Format(Hex(tmp(i)), "0#") Next End FunctionPrivate Sub Form_Load() Debug.Print StrToHex("字符串转16进制") End Sub输出结果:575B267B324E6C8F3136DB8F3652
Private Function StrToHex(ByVal s As String) As String
Dim buff() As Byte
Dim result As String
Dim tmps As String
'先将字串转换为byte数组,一个中文字符占两个字节,一个英文字符占一个字节
buff = StrConv(s, vbFromUnicode)
Dim i As Long
For i = 0 To UBound(buff)
'将各个字节转化为hex字串(每个字节两个字符,不足的前面补0)
tmps = Right("00" + Hex(buff(i)), 2)
'连接各个hex字串
result = result + tmps
Next
StrToHex = result
End FunctionPrivate Sub Command1_Click()
'测试
Dim s As String
s = "这是一个test"
Dim s1 As String
s1 = StrToHex(s)
MsgBox s1
End Su
Dim i As Long, tmp() As Byte: tmp = xStr
For i = 0 To UBound(tmp)
StrToHex = StrToHex & Format(Hex(tmp(i)), "0#")
Next
End FunctionFunction HexToStr(xHex As String) As String
Dim i As Long, tmp() As Byte
ReDim tmp(Len(xHex) / 2) As Byte
For i = 0 To UBound(tmp)
tmp(i) = Val("&H" & Mid(xHex, i * 2 + 1, 2))
Next
HexToStr = tmp
End FunctionPrivate Sub Form_Load()
Debug.Print StrToHex("字符串转16进制")
Debug.Print HexToStr("575B267B324E6C8F31003600DB8F3652")
End Sub
Dim i As Long, tmp() As Byte: tmp = xStr
For i = 0 To UBound(tmp)
If tmp(i) Then StrToHex = StrToHex & Format(Hex(tmp(i)), "0#")
Next
End FunctionPrivate Sub Form_Load()
Debug.Print StrToHex("字符串转16进制")
End Sub输出结果:575B267B324E6C8F3136DB8F3652