0

所以我的问题是在两台不同的计算机之间,我与字符串的连接不再可以打开连接。

这是我所拥有的:

Dim sFileName As String
Dim sFilePath As String

sFileName = "DataSource.xls"
sFilePath = "C:\test\testingData\"

Dim sConn As String
sConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=" & sFilePath & sFileName & ";" & _
        "Extended Properties=""Excel 8.0;HDR=Yes"";"

Dim errorObject As ADODB.Error
Set errorObject = CreateObject("ADODB.Error")

On Error GoTo ErrorDisplay:

Dim conn As ADODB.Connection

Set conn = New ADODB.Connection
conn.Open sConn

Dim rst As ADODB.Recordset '* Record Set
Set rst = New ADODB.Recordset

rst.Open sSql, conn, adOpenForwardOnly

Worksheets(1).Range("A2").CopyFromRecordset rst

sSQL = "SELECT * FROM [MySheet$] WHERE [Status] = 2 AND [DocNo] LIKE '%-A%'

当我在一台计算机上运行这部分代码时,它会在我构建它时完美运行。当我在类似的计算机上尝试它时,它不断给出错误"Object variable or With Block variable not set"。我发现问题出在conn.Open sConn上,但不确定是什么原因造成的。

我一直在寻找解决方案,但到目前为止我还没有找到任何有效的方法。

附加信息:
两台计算机:
Windows 7 x64
Excel 2007 x32

关于为什么这不起作用的任何想法?

--更新: 我刚刚在第三台 Windows 7 计算机上尝试了带有宏的 excel 文件,并且工作正常。

--更新: 我刚刚尝试从

sFilePath = "C:\Users\FirstName.LastName\Desktop\"

sFilePath = "C:\Users\FirstName.LastName\Desktop\Test\"

我真正想知道的是它是从“C:\Users\FirstName.LastName\Desktop\Test\”工作的,但其他都没有???

4

2 回答 2

0

You may try below code.

' Add reference to Adodb library
    Dim conn As ADODB.Connection

    Public Function CreateConnection() As Boolean
        On Error GoTo ErrorRet

        Dim X As Integer
        Dim sConn As String
        Dim sFileName As String
        Dim sFilePath As String

        X = 0
    Reconn:
        X = X + 1

        sFileName = "DataSource.xls"
        sFilePath = "C:\test\testingData\"

        sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source=" & sFilePath & sFileName & ";" & _
                "Extended Properties=""Excel 8.0;HDR=Yes"";"

        Set conn = New ADODB.Connection
        conn.Open sConn

        CreateConnection = True
        Exit Function

    ErrorRet:
        If Err.Number = -2147467259 Then
            GoTo Reconn
        Else
            If X > 5 Then
                CreateConnection = False
            Else
                GoTo Reconn
            End If
        End If
    End Function

    Sub test()

        Dim sSql As String
        Dim rst As ADODB.Recordset
        Set rst = New ADODB.Recordset

        If CreateConnection Then
            sSql = "SELECT * FROM [MySheet$]"
            rst.Open sSql, conn
            Worksheets(1).Range("A2").CopyFromRecordset rst

        End If

    End Sub
于 2013-06-12T23:40:05.000 回答
0

您确定两台计算机上都安装了主互操作程序集吗?

于 2013-06-12T21:18:26.203 回答