gpt4 book ai didi

excel - VBA - 从 Access 生成 Excel 文件(查询表)

转载 作者:行者123 更新时间:2023-12-01 22:49:13 25 4
gpt4 key购买 nike

我有一个项目,基本上目标是使用 VBA 在 Access 中单击按钮来生成 Excel(报告)。

此报告的内容是存储过程 SQL Server 数据库的结果。

错误行:

With MeuExcel.Worksheets(4)
.QueryTables.Add connection:=rs, Destination:=.Range("A2")
End With

我得到的是:

invalid procedure call or argument (erro '5')

完整代码(使用 Remou 用户提示编辑):

Sub GeraPlanilhaDT()

Dim MeuExcel As New Excel.Application
Dim wb As New Excel.Workbook

Set MeuExcel = CreateObject("Excel.Application")
MeuExcel.Workbooks.Add

MeuExcel.Visible = True

Dim strNomeServidor, strBaseDados, strProvider, strConeccao, strStoredProcedure As String

strNomeServidor = "m98\DES;"
strBaseDados = "SGLD_POC;"
strProvider = "SQLOLEDB.1;"
strStoredProcedure = "SP_ParametrosLeads_DT"

strConeccao = "Provider=" & strProvider & "Integrated Security=SSPI;Persist Security Info=True;Data Source=" & strNomeServidor & "Initial Catalog=" & strBaseDados

Dim cnt As New ADODB.connection
Dim cmd As New ADODB.command
Dim rs As New ADODB.recordset
Dim prm As New ADODB.parameter

cnt.Open strConeccao

cmd.ActiveConnection = cnt
cmd.CommandType = adCmdStoredProc
cmd.CommandText = strStoredProcedure
cmd.CommandTimeout = 0

Set prm = cmd.CreateParameter("DT", adInteger, adParamInput)
cmd.Parameters.Append prm
cmd.Parameters("DT").Value = InputBox("Digite o Código DT", "Código do Distribuidor")

Set rs = cmd.Execute()

Dim nomeWorksheetPrincipal As String
nomeWorksheetPrincipal = "Principal"

Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = nomeWorksheetPrincipal



With MeuExcel.Worksheets(4)
.QueryTables.Add connection:=rs, Destination:=.Range("A2")
End With


cnt.Close
Set rs = Nothing
Set cmd = Nothing
Set strNomeServidor = Nothing
Set strBaseDados = Nothing
Set strProvider = Nothing

If (ActiveSheet.UsedRange.Rows.Count > 1) Then
FormataDadosTabela
Else
MsgBox ("Não foi encontrado nenhum Distribuidor com esse DT")
End If


End Sub

奇怪的是,代码在 Excel 中运行时可以运行,但在 Access 中运行时不起作用

最佳答案

在 Access 中,您需要为 Excel 应用程序对象添加 Excel 应用程序实例的前缀,例如:

With MeuExcel.Worksheets(4).QueryTables.Add( _
connection:=recordset, _
Destination:=Range("A2"))
End With

此外,除非您有对 Excel 库的引用,否则 ypu 将需要提供内置 Excel 常量的值。

使用对象的名称作为变量是一个非常糟糕的主意。不要说:

Dim recordset As recordset
Set recordset = New recordset

例如说:

Dim rs As recordset

或者更好:

Dim rs As New ADODB.Recordset

如果您有合适的引用。然后您可以跳过 CreateObject。

编辑

该提供程序必须是 Access OLEDB 10 提供程序,用于绑定(bind)记录集。这适用于我使用 SQL Server 通过 Access 创建数据表:

strConnect = "Provider=Microsoft.Access.OLEDB.10.0;Persist Security Info=True;" _
& "Data Source=XYZ\SQLEXPRESS;Integrated Security=SSPI;" _
& "Initial Catalog=TestDB;Data Provider=SQLOLEDB.1"

关于excel - VBA - 从 Access 生成 Excel 文件(查询表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8716451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com