tags:

views:

151

answers:

1

I am working with the Microsoft OLE DB Provider for Jet to execute queries on spreadsheets in Excel using VBA. Is there a way to execute the following code on an unsaved workbook?

For example, ActiveWorkbook.FullName returns "Book1" if the workbook has never been saved. In that case the Data Source will assume the path is the active directory, and error out because the file was never saved.

Is there any way to use the Excel temporary file as the Data Source for Jet? I would like to test this but I don't even know how to return the Path and Name for the Excel temporary file.

Public Sub LocalJetQuery()

    Dim objStartingRange As Range
    Dim objConnection As New ADODB.Connection
    Dim objRecordset As New ADODB.Recordset

    Dim strDSN As String
    Dim strSQL As String

    Set objStartingRange = Application.Selection

    If CLng(Application.Version) >= 12 Then
        strDSN = "Provider=Microsoft.ACE.OLEDB.12.0;" _
        & "Data Source=" & objStartingRange.Worksheet.Parent.FullName & ";" _
        & "Extended Properties=""Excel 12.0 Xml;HDR=No;IMEX=1"";"
    Else
        strDSN = "Provider=Microsoft.Jet.OLEDB.4.0;" _
        & "Data Source=" & objStartingRange.Worksheet.Parent.FullName & ";" _
        & "Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"
    End If

    strSQL = "SELECT * FROM [" & objStartingRange.Worksheet.Name & "$];"

    objConnection.Open strDSN
    objRecordset.Open strSQL, objConnection

    Application.Workbooks.Add(xlWBATWorksheet).Sheets(1).Cells(1, 1).CopyFromRecordset objRecordset

End Sub

Thanks!

A: 

No. Just like David Fenton says in the comments.

MarkJ
@MarkJ: forgot this was unanswered. Thanks!
Kuyenda