Excel VBA query for a closed workbook

南笙酒味 提交于 2020-01-03 02:40:09

问题


I've been trying to adapt excel VBA queries for retreiving data from a closed workbook as an alternative option. I found a sample code online and I adjusted it as I thought to fit my needs. After frusterating few hours I can't quite figure out why it will not work.

When I try to specify a table I get the error "Microsoft access database engine cannot find the object 'CompanyInFo' ... I tried replacing it with a defined name range aswell and still receive the same error.

Heres the Code:

 Sub DataLookup()

Dim str As String
Dim Recset As ADODB.Recordset
Dim query As String

Dim fileName As String
fileName = ActiveWorkbook.Sheets("DataValidation").Range("D18")

str = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
           "Data Source=" & fileName & ";" & _
           "Extended Properties=Excel 12.0"


query = "SELECT CompanyName FROM CompanyInFo"
    'Tried SELECT [CompanyName].[CompanyInFO] FROM [CompanyInFo]
    '      SELECT * From [CompanyInFo]
    ' Works SELECT * FROM [Cell Validation$] <--- Sheet

 'Error Prompts here 
Set Recset = New ADODB.Recordset
Recset.Open query, str



Cells.Clear
Range("A2").CopyFromRecordset Recset

Dim cell As Range, i As Long
With Range("A1").CurrentRegion
    For i = 0 To Recset.Fields.Count - 1
        .Cells(1, i + 1).Value = Recset.Fields(i).Name
    Next i
    .EntireColumn.AutoFit
End With
End Sub

The tablename is "CompanyInFo" and it is located on a sheet called "Cell Validation". I wanted to reference a table as the list is updated daily with additions and sometimes removals. Mentioned before I did try creating a dynamic named range but I still received the same issues?

My thoughts: 1. I Could be missing a reference? 2. I am mis using th ADODB?

Any help or guidance is appreciated! Alex

来源:https://stackoverflow.com/questions/20267766/excel-vba-query-for-a-closed-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!