【发布时间】:2018-03-06 19:13:14
【问题描述】:
我正在尝试使用单元格值将文本文件导入 Excel 工作簿,以确定要导入的文本文件。包含文本文件的目录将包含其他文本文件,其文件名前带有日期。 (例如“2018-03-06-FILENAME.txt”)
我希望用户能够在预定义的单元格中输入日期,并能够运行一个宏来检查该单元格的值,然后导入与该值匹配的文件。我想我的代码遇到了问题,它看到的是日期代码,而不是文件名的值。不知道如何解决这个问题? (用户必须能够以人性化的方式输入日期,而不是“43164”。)
Sub Import()
Dim currentPath As String
Dim newPath As String
Dim currentFile As String
Dim currentDate As String
currentPath = "\\network\folder\"
newPath = "\\network\folder\Processed\"
' Get the first file
currentDate = Sheet1.Range("A1").Value
currentFile = Dir(currentPath & currentDate & "*.txt")
Do While currentFile <> ""
' Clear previous data
Sheet2.Activate
ActiveSheet.UsedRange.Clear
Range("A1").Select
' Process text file
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & currentPath & currentFile, _
Destination:=Range("$A$1"))
.Name = "Data"
.FieldNames = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = True
.TextFileColumnDataTypes = Array(3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.Refresh BackgroundQuery:=False
End With
ActiveSheet.QueryTables(1).Delete
' Move file into Processed folder
Name currentPath & currentFile As newPath & currentFile
' Get the next file
currentFile = Dir
Loop
End Sub
【问题讨论】:
-
Excel 中的日期值是一个数字,而不是文本。有关可能的解决方案,请参阅此 SO 帖子。 stackoverflow.com/questions/36507562/…