在 Excel VBA 中将字符串转换为十六进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26363113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:02:16  来源:igfitidea点击:

Converting String to Hex in Excel VBA

excelvbaexcel-vba

提问by Tanvir

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?

Convert.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”,我如何将其转换为十六进制以便我可以对其执行十六进制计算?

回答by Alex K.

In VBA you need to mess about with the &Hliteral:

在 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)

回答by Gary's Student

Consider:

考虑:

Sub dural()
    Dim val As String, hval As String
    val = "10"
    hval = Application.WorksheetFunction.Dec2Hex(val)
    MsgBox hval
End Sub

VBAcode needs to know or make an assumption about the input string. The code above assumes that the string represents a decimalvalue.

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 hvalcan be used arithmetically.

这里hval可以在算术上使用。