excel - 如何动态更改文件路径中的文件名?
问题描述
我想将多个 TXT 文件导入到 excel 中(导入到同一张表中 - 每个文件只有 6 行)。如何在每个周期中更改文件路径(我将在 for 周期中进行)?
Sub openfile()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\HarrsionDavid\Desktop\\source\customer.txt", _
Destination:=Range("A1"))
.Name = "customer.txt"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1250
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 9, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Range("A1:C3").Selection
Selection.Delete Shift:=x1Up
Range("A1:C3").Selection
Selection.Delete Shift:=x1Up
End Sub
在这个问题(Import multiple text files into excel)中有一个答案,但我只需要在路径中更改文件名,因为文件名将从其他 excel 列中获取。在 Google 和 Stackoveflow 上,我什么也没找到。
解决方案
您可以使用字符串变量作为文件名,并将其附加到硬编码文件路径:
Sub openfile(ByVal sFileName As String)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\HarrsionDavid\Desktop\\source\" & sFileName, _
Destination:=Range("A1"))
.Name = "customer.txt"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1250
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 9, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Range("A1:C3").Selection
Selection.Delete Shift:=xlUp
Range("A1:C3").Selection
Selection.Delete Shift:=xlUp
End Sub
然后通过传递文件名调用:
Sub TestOpenFile()
openfile "customer.txt"
End Sub
推荐阅读
- javascript - Vuejs keyup,条码读取13次以上
- angularjs - 在 ng-if 更改后强制元素重新渲染
- google-bigquery - 无法在 BigQuery 中运行多个 CTE
- prolog - 如何使用 Aleph 和 SWI-Prolog 输出理论?
- sql - Oracle CASE WHEN 短路返回表达式
- powershell - 使用 Powershell 替换文本文件中的路径
- karate - 空手道是否支持 .avro 文件作为输入请求?
- ubuntu - 无法在 Ubuntu 上更新 QGIS
- mapbox-gl-js - 在地图框中的圆圈悬停时显示弹出窗口
- xcode - Xcode中如何隐藏调用栈中的第三方调用