Is it possible to search for, then to read in specific values from an Excel file using Access VBA?
-
21-12-2019 - |
Question
I have had to read in values from an excel file before, but it was a Excel comma separated file. This time I have an excel file with a graph and two tables. I only want to read in the values in one column of a specific table. Here is a picture of the layout of the excel file. I would like to read in the column marked "Amount" in the bottom table marked by a red arrow. I do not want to read in the total of all the amounts below it.
When I was reading in all values from a excel comma separated file I used this code. Initializations and unnecessary logic have been removed to only show the relevent code to this question.
Set objconnection = CreateObject("ADODB.connection")
Set objRecordset = CreateObject("ADODB.recordset")
objconnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strpathtotextfile & ";Extended Properties=""Text;HDR=YES;FMT=Delimited"""
objRecordset.Open "SELECT * FROM [" & ThisFileName & "]", objconnection, adOpenStatic, adLockOptimistic, adCmdText 'select all text lines from the file
Do While Not objRecordset.EOF 'read lines until end of file
'Clear out all the local objects so prior values aren't left there'
SampleName = ""
DateTimeAcquired = ""
Analyte = ""
Concentration = ""
'reads in each value according to column name and save to variable'
SampleName = objRecordset.Fields("Sample Name").Value
DateTimeAcquired = objRecordset.Fields("Date and Time Acquired").Value
Analyte = objRecordset.Fields("Element Full Name").Value
Concentration = objRecordset.Fields("Concentration").Value
'other logic'
objRecordset.MoveNext
Loop
Is there something similar I can do for the excel file I am currently trying to import? Is there a way to only import that one column?
UPDATE: the excel files are always in the same layout as in I am always retrieving information from slots 29G-34G.
Solution
You'll need to adjust the file path and sheet name, but something like this should work:
Sub Tester()
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\thisuser\Desktop\test.xlsx;" & _
"Extended Properties=""Excel 12.0 Xml;HDR=NO"""
Set rs = cn.Execute("select * from [Sheet1$G29:G34]")
Do While Not rs.EOF
Debug.Print rs(0).Value
rs.MoveNext
Loop
End Sub