【发布时间】:2018-03-10 21:05:12
【问题描述】:
我正在运行这个模块,但它一直给我一个错误,并且调试将我发送到这一行:
Set oSHA1 = CreateObject("System.Security.Cryptography.SHA1Managed")运行时错误'-2146233079(80131509':自动化错误)
我添加了对mscorlib 类型库的引用,但它仍然无法正常工作。
Public Function SHA1(sIn As String, Optional bB64 As Boolean = 0) As String
'Set a reference to mscorlib 4.0 64-bit
'Test with empty string input:
'40 Hex: da39a3ee5e6...etc
'28 Base-64: 2jmj7l5rSw0yVb...etc
Dim oT As Object, oSHA1 As Object
Dim TextToHash() As Byte
Dim bytes() As Byte
Set oT = CreateObject("System.Text.UTF8Encoding")
Set oSHA1 = CreateObject("System.Security.Cryptography.SHA1Managed")
TextToHash = oT.GetBytes_4(sIn)
bytes = oSHA1.ComputeHash_2((TextToHash))
If bB64 = True Then
SHA1 = ConvToBase64String(bytes)
Else
SHA1 = ConvToHexString(bytes)
End If
Set oT = Nothing
Set oSHA1 = Nothing
End Function
Private Function ConvToBase64String(vIn As Variant) As Variant
Dim oD As Object
Set oD = CreateObject("MSXML2.DOMDocument")
With oD
.LoadXML "<root />"
.DocumentElement.DataType = "bin.base64"
.DocumentElement.nodeTypedValue = vIn
End With
ConvToBase64String = Replace(oD.DocumentElement.Text, vbLf, "")
Set oD = Nothing
End Function
Private Function ConvToHexString(vIn As Variant) As Variant
Dim oD As Object
Set oD = CreateObject("MSXML2.DOMDocument")
With oD
.LoadXML "<root />"
.DocumentElement.DataType = "bin.Hex"
.DocumentElement.nodeTypedValue = vIn
End With
ConvToHexString = Replace(oD.DocumentElement.Text, vbLf, "")
Set oD = Nothing
End Function
我在代码中更改了这个
'Set oT = CreateObject("System.Text.UTF8Encoding")
'Set oSHA1 = CreateObject("System.Security.Cryptography.SHA1Managed")
With New UTF8Encoding
TextToHash = .GetBytes_4(sIn)
End With
With New SHA1Managed
bytes = .ComputeHash_2((TextToHash))
End With
现在我遇到了同样的错误,但在使用新的 SHA1Managed
这就是我现在拥有代码的方式,但在 With New SHA1Managed 上仍然出现错误
公共函数 SHA1(sIn As String, Optional bB64 As Boolean = 0) As String '设置参考
'Test with empty string input:
'40 Hex: da39a3ee5e6...etc
'28 Base-64: 2jmj7l5rSw0yVb...etc
Dim oT As Object, oSHA1 As Object
'Dim TextToHash() As Byte
'Dim bytes() As Byte
'Set oT = CreateObject("System.Text.UTF8Encoding")
'Set oSHA1 = CreateObject("System.Security.Cryptography.SHA1Managed")
With New UTF8Encoding
TextToHash = .GetBytes_4(sIn)
End With
With New SHA1Managed
bytes = .ComputeHash_2((TextToHash))
End With
TextToHash = oT.GetBytes_4(sIn)
bytes = oSHA1.ComputeHash_2((TextToHash))
If bB64 = True Then
SHA1 = ConvToBase64String(bytes)
Else
SHA1 = ConvToHexString(bytes)
End If
Set oT = Nothing
Set oSHA1 = Nothing
结束函数
我更改了对 v2.05 mscorlib.tlb 的引用,但仍然遇到同样的错误
【问题讨论】:
-
你得到的确切错误是什么?
-
运行时错误 '-2146233079 (80131509': 自动化错误
-
en.wikibooks.org/wiki/Visual_Basic_for_Applications/… ,这是我顺便找到这段代码的地方
-
既然设置了对 mscorlib 的引用,为什么还要使用后期绑定?
-
除了@Mat'sMug 对后期绑定和早期绑定的解释之外,还有大量文章可以通过互联网搜索获得。如果您打算在 VBA 中进行任何高级编程,那么您需要了解它。