I need to convert strings to hexadecimals in my Excel VBA macro.
我需要在Excel VBA宏中将字符串转换为十六进制。
I tried:
我试着:
Dim val As String
val = "10"
Dim hexVal As Integer
hexVal = Convert.ToInt32(val, 16)
but Convert.ToInt32(val, 16)
does not work, I'm guessing because it's not VB.NET?
但转换。ToInt32(val, 16)不工作,我猜是因为它不是VB.NET?
Anyway, I can use CInt(val)
to convert a string to an integer but if I have the string representation of a hex value, e.g. "3366CC", how do I convert it to hex so that I can perform hex calculations on it?
无论如何,我可以使用CInt(val)将一个字符串转换成整数,但是如果我有一个十六进制值的字符串表示,例如。“3366CC”,如何将它转换为十六进制,以便对它进行十六进制计算?
2 个解决方案
#1
7
In VBA you need to mess about with the &H
literal:
在VBA中,你需要乱用&H文字:
value = val("&H" & "10") '// 16
value = val("&H3366CC") '// 3368652
Edit
编辑
Function FromHex(hexString As String) As Long
FromHex = Val("&H" & hexString)
End Function
Then
然后
resultString = hex$(FromHex("3366CC") / FromHex("A"))
Or for constants obviously;
或常数明显;
resultString = hex$(FromHex("3366CC") / &HA)
#2
5
Consider:
考虑:
Sub dural()
Dim val As String, hval As String
val = "10"
hval = Application.WorksheetFunction.Dec2Hex(val)
MsgBox hval
End Sub
VBA code needs to know or make an assumption about the input string. The code above assumes that the string represents a decimal value.
VBA代码需要知道或假设输入字符串。上面的代码假设字符串表示一个十进制值。
If the input string is Hex, then:
如果输入字符串为十六进制,则:
Sub dural2()
Dim val As String, hval As Long
val = "10"
hval = Application.WorksheetFunction.Hex2Dec(val)
MsgBox hval
End Sub
Here hval can be used arithmetically.
在这里,hval可以算术地使用。
#1
7
In VBA you need to mess about with the &H
literal:
在VBA中,你需要乱用&H文字:
value = val("&H" & "10") '// 16
value = val("&H3366CC") '// 3368652
Edit
编辑
Function FromHex(hexString As String) As Long
FromHex = Val("&H" & hexString)
End Function
Then
然后
resultString = hex$(FromHex("3366CC") / FromHex("A"))
Or for constants obviously;
或常数明显;
resultString = hex$(FromHex("3366CC") / &HA)
#2
5
Consider:
考虑:
Sub dural()
Dim val As String, hval As String
val = "10"
hval = Application.WorksheetFunction.Dec2Hex(val)
MsgBox hval
End Sub
VBA code needs to know or make an assumption about the input string. The code above assumes that the string represents a decimal value.
VBA代码需要知道或假设输入字符串。上面的代码假设字符串表示一个十进制值。
If the input string is Hex, then:
如果输入字符串为十六进制,则:
Sub dural2()
Dim val As String, hval As Long
val = "10"
hval = Application.WorksheetFunction.Hex2Dec(val)
MsgBox hval
End Sub
Here hval can be used arithmetically.
在这里,hval可以算术地使用。