excel - 使用文件路径中的单元格值循环遍历单元格并导入 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
:
我认为我没有正确使用循环中的变量。
解决方案
这是因为您实际上并未将 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
您指定的值。
推荐阅读
- c++ - 具有特征矩阵的 Stl 迭代器
- javascript - 悬停在循环 JS/jquery 中的一个元素会改变另一个元素
- javascript - 使用扫描线循环绘制填充多边形
- android - 片段事务后Android滚动视图保持滚动位置
- java - 为什么我的可执行 jar 找不到主类?
- javascript - 属性-属性同步
- java - ConcurrentHashMap 的 forEach 方法是线程安全的吗?
- asp.net-mvc - 模态形式未显示为模态
- mysql - mysql对多行特定条件进行排名
- python-3.x - ImportError:没有系统模块'pywintypes'(pywintypes39.dll)