首页 > 解决方案 > 使用文件路径中的单元格值循环遍历单元格并导入 CSV 文件

问题描述

我有一张表,资产名称在顶行,日期在第一列。

当前文件

我需要遍历第一行中的所有单元格,获取单元格的值并将其包含在文件路径中以从文本文件中导入第 6 列。

到目前为止,我有这个:

For i = 2 To HCP.Cells(1, HCP.Columns.Count).End(xlToLeft).Column
    If HCP.Cells(1, i).Value <> "" Then
        j = HCP.Cells(2, HCP.Columns.Count).End(xlToLeft).Column + 1
            With HCP.QueryTables.Add(Connection:="TEXT;" & Folder & "\" & i & "1440.CSV", Destination:=HCP.Cells(2, j + 1))
                .TextFileParseType = xlDelimited
                .TextFileCommaDelimiter = True
                .TextFileSpaceDelimiter = True
                .TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
                .Refresh BackgroundQuery:=False
                i = i + 1
            End With
    End If
Next

我得到了这个.Refresh BackgroundQuery:=False

错误信息

我认为我没有正确使用循环中的变量。

标签: excelvbaloopscsv

解决方案


这是因为您实际上并未将 i 设置为单元格中的任何值,它只是您的计数器。您需要设置HCP.Cells(1, i).Value一个变量并通过您的文件路径传递该变量。

尝试这个:

For i = 2 To HCP.Cells(1, HCP.Columns.Count).End(xlToLeft).Column

    rowContent = HCP.Cells(1, i).Value

    If rowContent <> "" Then
        j = HCP.Cells(2, HCP.Columns.Count).End(xlToLeft).Column + 1
            With HCP.QueryTables.Add(Connection:="TEXT;" & Folder & "\" & rowContent & "1440.CSV", Destination:=HCP.Cells(2, j + 1))
                .TextFileParseType = xlDelimited
                .TextFileCommaDelimiter = True
                .TextFileSpaceDelimiter = True
                .TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
                .Refresh BackgroundQuery:=False

            End With
    End If
Next

此外i = i + 1,您的代码中也不需要,它Next会自动将您的 i 编号增加到To您指定的值。


推荐阅读