Reading a workbooks without opening it with ADO

后端 未结 2 1856
孤城傲影
孤城傲影 2021-01-07 12:46

After this question: get value/charts in another workbooks without opening it

I have coded this:

Sub test()

Dim oConn As New ADODB.Connection
Dim r         


        
相关标签:
2条回答
  • 2021-01-07 13:03

    My solution:

    Function GetValue()
    
    Path = "C:\Path\"
        File = "Doc.xlsm"
        Sheet = "Sheet_name"
        Ref = "D4"
    
         'Retrieves a value from a closed workbook
        Dim Arg As String
         'Make sure the file exists
       If Right(Path, 1) <> "\" Then Path = Path & "\"
       If Dir(Path & File) = "" Then
           GetValue = "File not  Found"
           Exit Function
        End If
         'Create the argument
        Arg = "'" & Path & "[" & File & "]" & CStr(Sheet) & "'!" & Range(Ref).Range("A1").Address(, , xlR1C1)
         'Check the value
    
         MsgBox Arg
    
        'Execute XML
    
        GetValue = ExecuteExcel4Macro(Arg)
    End Function
    

    It has the advantage of not using complex adodb connection, but may be less powerfull.

    0 讨论(0)
  • 2021-01-07 13:09

    If you don't mind I'll provide you a bit different attempt to get your data. The difference is the way you connect with you database (excel sheet). However, you could possibly incorporate some important elements into your code. So, check comments inside the code below.

    Sub Closed_excel_workbook()
    
        Dim myConnection As String
        Dim myRecordset As ADODB.Recordset
        Dim mySQL As String
    
    'connection string parameters
    'CHANGE PATH TO YOUR CLOSED WORKBOOK
        myConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                   "Data Source=" & ThisWorkbook.Path & "\Dane\BazaDanych.xlsx;" & _
                   "Extended Properties=Excel 12.0"
    
    'here is important, YOU CAN'T MISS SHEET NAME
        mySQL = "SELECT * FROM [ARKUSZ1$a1:a2]"
    
    'different way of getting data from excel sheet
        Set myRecordset = New ADODB.Recordset
        myRecordset.Open mySQL, myConnection, adOpenUnspecified, adLockUnspecified
    
    'let's clear sheet before pasting data
    'REMOVE IF NOT NEEDED
        ActiveSheet.Cells.Clear
    
    'HERE WE PASTING DATA WE HAVE RETRIEVED
        ActiveSheet.Range("A2").CopyFromRecordset myRecordset
    
    'OPTIONAL, IF REQUIRED YOU CAN ADD COLUMNS NAMES
        Dim cell As Range, i!
        With ActiveSheet.Range("A1").CurrentRegion
            For i = 0 To myRecordset.Fields.Count - 1
                .Cells(1, i + 1).Value = myRecordset.Fields(i).Name
            Next i
            .EntireColumn.AutoFit
        End With
    End Sub
    
    0 讨论(0)
提交回复
热议问题