VBA Excel“自动化错误”来自SHA256和HMACSHA256函数

目前在我的代码行中得到一个自动化错误(注意,这个错误只发生在Windows 10上)

Set oUTF = CreateObject("System.Text.UTF8Encoding") Set oEnc = CreateObject("System.Security.Cryptography.SHA256Managed") 

这是完整的function

 Function HMACSHA256(strToSign As String, strKey() As Byte) Dim lngLoop As Long Dim oUTF, oEnc Dim HMAC() As Byte Dim lastrow As Long On Error GoTo err_handler Set oUTF = CreateObject("System.Text.UTF8Encoding") Set oEnc = CreateObject("System.Security.Cryptography.HMACSHA256") oEnc.key = strKey HMAC = oEnc.ComputeHash_2(oUTF.GetBytes_4(strToSign)) HMACSHA256 = HMAC Exit Function err_handler: Worksheets("Log Sheet").Cells(lastrow, 4) = "Fail" Worksheets("Log Sheet").Cells(lastrow, 5) = Err.Description MsgBox Err.Description, vbCritical End Function 

从我的testing和研究中,我发现这些线上的错误与.net框架4.6版本有关。 安装.netframework版本3.5修复此错误,并允许代码正确运行。 然而,这个电子表格是给客户,我宁愿有这个function,而不必要求客户端安装3.5(电子表格需要是所有的客户端需要使用其所有function,即他们不得不安装任何东西(办公室除外),都必须包含在excel文件中)

有谁知道这样做的另一种方式? 我find了一种使用类模块来完成SHA256的方法,但是这不起作用HMACSHA256。 我需要一种方法来做到这一点。

所以我最后自己解决了这个问题。 我发现了另一个类模块,它完成了以前由.net组件完成的所有工作

我在http://www.vbforums.com/showthread.php?635398-VB6-HMAC-SHA-256-HMAC-SHA-1-Using-Crypto-API上find了课程模块

这里是我更新的代码:

 Function HMACSHA256A(strToSign As String, strKey() As Byte) Dim lngLoop As Long Dim oUTF, oEnc Dim HMAC() As Byte Dim lastrow As Long Dim byteString() As Byte On Error GoTo err_handler lastrow = FindLastRow Set Test = New HS256 Test.InitHmac strKey byteString = Test.ToUTF8(strToSign) HMACSHA256A = Test.HMACSHA256(byteString) Worksheets("Log Sheet").Cells(lastrow, 4) = "Pass" Exit Function err_handler: Worksheets("Log Sheet").Cells(lastrow, 4) = "Fail" Worksheets("Log Sheet").Cells(lastrow, 5) = Err.Description MsgBox Err.Description, vbCritical End Function