VBA 使用 ADO 调用带参数的存储过程

标签 vba stored-procedures ado

我正在尝试使用 ADO 在 VBA 中调用带有两个参数的 SQL Server 存储过程;但是我收到错误消息“运行时错误‘13’类型不匹配”。我花了几个小时在网上搜索,但就是无法正常工作...... 这是我的代码:

Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command

cnn.ConnectionString = "Provider=SQLNCLI11;" _
                 & "Server=(Local);" _
                 & "Database=Inventory;" _
                 & "Integrated Security=SSPI;" _
                 & "DataTypeCompatibility=80;"
cnn.Open

With cmd
    .ActiveConnection = cnn
    .CommandType = "adCmdText"
    .CommandText = "usp_mySP"
    .Parameters.Append .CreateParameter("@fileName1", adChar, adParamInput, , File1.Name)
    .Parameters.Append .CreateParameter("@fileName2", adChar, adParamInput, , File2.Name)
    .Execute
End With

File1.NameFile2.Name 是我使用 FileSystemObject 获得的两个最新修改文件的名称。

usp_mySP 是我的存储过程,它主要使用 bcp 命令导出制表符分隔的文件。它在 SQL Server 中运行良好。

有什么建议或意见吗?

最佳答案

又经过几个小时的反复试验,我终于让代码正常工作了。并感谢 @Mat 指出将 adChar 更改为 adVarChar

Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command

cnn.ConnectionString = "Provider=SQLNCLI11;" _
             & "Server=(Local);" _
             & "Database=Inventory;" _
             & "Integrated Security=SSPI;" _
             & "DataTypeCompatibility=80;"
cnn.Open

With cmd
    .ActiveConnection = cnn
    .CommandType = adCmdStoredProc
    .CommandText = "usp_mySP"
    .Parameters.Append .CreateParameter("@fileName1", adVarChar, adParamInput, 50, File1.Name)
    .Parameters.Append .CreateParameter("@fileName2", adVarChar, adParamInput, 50, File2.Name)
    .Execute
End With
MsgBox"Thank God! Finally it's working!"
cnn.Close

关于VBA 使用 ADO 调用带参数的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401206/

相关文章:

vba - "Unable to get the VLookup property of the WorksheetFunction Class"错误

vba - 如何在 VBA 中将工作表从一个工作簿移动到另一个工作簿

vba - 从excel填充word文档而不删除书签

excel - Access VBA如何判断文件是否是Excel格式?

sql-server - VBScript/ASP Classic 和 ADO 中的参数化

Mysql游标在存储过程中不返回任何内容

mysql - 为什么这个存储过程在查询本身不返回多行时返回多行?

c# - SM?使用 if exists drop then create 和 no sp_executesql 编写所有 SQL 存储过程的脚本

c++ - 显示不同值的列数

mysql - 如何在 ADO.NET 中使用 MySQL 用户变量