VBA / ADO QUERY在我的计算机上运行并在同事计算机上失败

时间:2016-03-17 18:14:18

标签: sql excel vba ado

以下代码在我的计算机上运行良好。我不明白为什么它不在另一台人的电脑上工作。有人可以引导我提出可能有助于解决问题的想法吗? 错误(显示错误时出错)是数组没有加载数据。得到类似&#34的错误; bof或eof对于当前记录都是正确的"

此外,我可以告诉你,如果错误GoTo NEXTT仍然打开..它去那里并尝试擦除数组并返回错误的数据类型错误。让我觉得数组是空的。

我检查了Conn.State,我可以确认连接已打开。

Function sbADO(ban_id, upc_id, div_id)
'Must add Activex data objects libaray 2.8
Dim sSQLSting As String
On Error GoTo nextt

Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset

Dim DBPath As String, sconnect As String



DBPath = ThisWorkbook.FullName

'You can provide the full path of your external file as shown below


sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

Conn.Open sconnect
sSQLSting = "SELECT * From [data$] where BANNER_ID IN (" & ban_id & ") AND UPC_ID IN (" & upc_id & ") AND DIVISION_ID IN (" & div_id & ") " 'Your SQL Statemnt (Table Name= Sheet Name=[DataSheet$])

    mrs.Open sSQLSting, Conn
        '=>Load the Data into an array
        ReturnArray = mrs.GetRows
                ''OR''
        '=>Paste the data into a sheet
        'Sheets("Sheet1").Range("A2").CopyFromRecordset mrs
    'Close Recordset
    mrs.Close

'Close Connection
Conn.Close

'
Exit Function
nextt:
Erase ReturnArray
'mrs.Close
Conn.Close
    'MsgBox (ReturnArray(6, 2)) '(feild, row)

End Function

2 个答案:

答案 0 :(得分:0)

问题是因为 DBPath = ThisWorkbook.FullName< - 工作簿设置为只读。 删除只读状态可以解决问题。

答案 1 :(得分:0)

您似乎正在使用ADO查询相同工作簿中的数据?这可能是为了简化SO的这个问题,但通过直接引用范围来获得所需的数组会更容易,更快捷。但在这个答案中,我假设您确实想要使用ADO。

您尝试使用ADO打开工作簿,但是您没有使用任何只读参数指定ConnectionString或Open方法。尝试进行这些调整:

'Add Mode=Read

sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath & _
";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";Mode=Read;"

'Add adLockReadOnly
mrs.Open sSQLSting, Conn, , adLockReadOnly