是否可以使用Access VBA搜索,然后从Excel文件中读取特定值?

时间:2014-07-30 18:25:02

标签: excel vba excel-vba access-vba

之前我必须从excel文件中读取值,但它是一个Excel逗号分隔文件。这次我有一个带有图表和两个表的excel文件。我只想读入特定表的一列中的值。这是excel文件布局的图片。我想在标有" Amount"的栏目中阅读。在底部表中标有红色箭头。我不想读下面所有金额的总和。

enter image description here

当我从excel逗号分隔文件中读取所有值时,我使用了此代码。已删除初始化和不必要的逻辑,仅显示此问题的相关代码。

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

我目前正在尝试导入的excel文件是否有类似的功能?有没有办法只导入那一列?

更新:excel文件始终采用与我始终从插槽29G-34G中检索信息相同的布局。

1 个答案:

答案 0 :(得分:2)

您需要调整文件路径和工作表名称,但这样的方法应该有效:

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