从Excel中的多个txt文件访问和获取值

时间:2014-01-15 12:36:54

标签: excel vba excel-vba

我在一年中的每一天都有一个以表格(行和标签)组织的txt文件,即2013-01-01.txt,2013-01-02.txt等等。

我想在此文件中VLOOKUP()价格列获取产品价格。我的工作表将如下所示:

+------------+------------+------------+------------+------------+
|   Price    | 2013-12-26 | 2013-12-27 | 2013-12-30 | 2013-12-31 |
+------------+------------+------------+------------+------------+
| Watermelon | 1          | 1.5        | 1.35       | 1.85       |
| Botato     | 0.55       | 0.65       | 0.55       | 0.8        |
+------------+------------+------------+------------+------------+

我可以想象两个选项:

  1. 使用Workbooks.Open()打开哪个文件获取我需要的值然后关闭文件:

    Workbooks.Open (Path)
    'Get values
    Workbooks.Close
    
  2. 中打开更新文件
    With ActiveSheet.QueryTables.Add(Connection:= ...)
        .name = path
    End With
    'Get values
    ActiveWorkbook.Connections(Path).Delete
    
  3. 有人以另一种方式思考实施吗?哪一个更快并且更好理解?

1 个答案:

答案 0 :(得分:1)

如果您想在Excel中打开每个文件而不使用TextStream,那么以下代码可以帮助您:

Sub OpenTxtFileInExcel()

Dim basicWorkbook, actWorkbook As Workbook
Dim basicSheet, actSheet As Worksheet
Dim filePath As String
Dim actDate As Date
Dim searchedProduct As String
Dim counterColumn, counterRow As Integer
Dim products As Variant
products = Array("Lemon", "Mango", "Durian")

Set basicWorkbook = Application.ActiveWorkbook
Set basicSheet = basicWorkbook.Worksheets(1)

actDate = CDate("01-01-2013")
counterColumn = 0

Do While actDate < CDate("01-01-2014")
    filePath = Format(actDate, "yyyy-MM-dd") & ".txt"
    Workbooks.OpenText Filename:=filePath, Origin:= _
        xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
        , ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:= _
        True, Space:=False, Other:=True, OtherChar:=False

    Set actWorkbook = Application.ActiveWorkbook
    Set actSheet = basicWorkbook.Worksheets(1)

    basicSheet.Range("B1").Offset(0, counterColumn).Value = Format(actDate, "yyyy-MM-dd")
    For counterRow = 0 To UBound(products)
        basicSheet.Range("A2").Offset(counterRow, 0).Value = products(counterRow)
        basicSheet.Range("B2").Offset(counterRow, counterColumn).Value = _
            Application.WorksheetFunction.VLookup(products(counterRow), actSheet.Range("A:B"), 2, False)
    Next counterRow

    actWorkbook.Close

    counterColumn = counterColumn + 1
    actDate = DateAdd("d", 1, actDate)
Loop

End Sub 

命令Workbooks.OpenText非常依赖于文本文件的结构,您应该在打开时记录此命令(在Excel 2007/2010:View&gt; Macros&gt; Record Macor ...中)文本文件只是通过Excel以vlookup可以工作的方式。