vba Excel数据连接

时间:2016-05-10 14:10:32

标签: excel-vba vba excel

我需要一些帮助。我有一个工作簿(A),我想打开另一个工作簿(B)并运行一个在B里面的宏。 工作簿(B)有一个宏,它使一个SQL连接到另一个工作簿(C)来提取数据,当我在工作簿(B)中运行此宏工作正常,但如果我从工作簿(A)打开工作簿(B)并运行宏我从Windows“文件打开”(WorkBooK(C))收到一条消息。 我该如何跳过此消息。

enter image description here

打开连接数据时出现错误。

打开工作簿(B)的代码是:

    Sub OpenWorkBookandRun()
    tarPath = "..............\"
    strfilename = "..........xlsm"

    Application.Workbooks.Open tarPath & strfilename
    'Run Macro
    Workbooks(strfilename).Activate
    Application.Run "'................'!Module1.Macro"
    ActiveWorkbook.Save
    ActiveWorkbook.Close
End Sub

工作簿(B)中打开数据源的代码是:

    ' Establezco los parametros de la conexion ADO, el RecordSet y la Cadena de conexion
Set oCONN = New ADODB.Connection
Set oRS = New ADODB.Recordset
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & OrigDatos & ";Extended Properties=""Excel 12.0;HDR=Yes;"";"
' Abro la conexion y ejecuto la sentencia SQL
If Not (oCONN Is Nothing) Then
  If (oCONN.State And adStateOpen) = adStateOpen Then oCONN.Close
End If
oCONN.Open strConn  <--- Line where i get the error
oRS.Open strSQL, oCONN, 1, 3

请注意。有时在fisrt工作簿中,我得到相同的消息,但有时只有我不知道为什么因为任何人都有数据的来源打开

2 个答案:

答案 0 :(得分:0)

从Workbook(A)运行宏时,工作簿(C)是否已打开? 其他问题是,你需要在工作簿(C)中写一些东西吗?如果不这样做,您可以使用连接字符串中的参数与readonly连接,如下所示:

strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Data Source=" & OrigDatos & ";Extended Properties=""Excel 12.0;HDR=Yes;""

答案 1 :(得分:0)

尝试设置Notify = false。

Application.Workbooks.Open tarPath & strfilename, , , , , , , , , ,false

根据MSDN,通知提示具有以下功能, &#34;如果无法以读/写模式打开文件,则此参数为True以将文件添加到文件通知列表中。 Microsoft Excel将以只读方式打开文件,轮询文件通知列表,然后在文件可用时通知用户。如果此参数为False或省略,则不会请求通知,并且任何打开不可用文件的尝试都将失败。&#34;