我正在尝试使用单元格值将文本文件导入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
currentDate = Sheet1.Range("A1").Value
确实会给出Excel用于存储日期的顺序日期I.E.(43261)
请改用currentDate = Format(Sheet1.Range("A1").text, "YYYY-MM-DD") & "FILENAME.txt"
。
您还可以使用debug.print currentdate
检查变量中存储的内容,然后使用Ctrl+G
for console在宏执行后显示打印值。
我强烈建议使用instr
函数来查找文件名中的日期,而不是直接比较它们,除非您的文件日期不是唯一的。还要记住使用TextCompare模式进行非大小写敏感的比较。
示例:If instr(1, CURRENT FILENAME STRING, currentDate, vbTextCompare) then
'if filename is found then code goes here.
end if
尝试
Format$(Sheet1.Range("A1").Value,"yyyy-mm-dd")
虽然,根据您的示例,您的代码中应该有-FILENAME位吗?
你要
2018-03-06-FILENAME.txt
但只给:
currentPath & currentDate & ".txt"
所以,需要currentPath & "-" & currentDate & "-" & FILENAME & ".txt"
假设FILENAME是一个变量。