【问题标题】:Use cell value (date) to import text file使用单元格值(日期)导入文本文件
【发布时间】: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

【问题讨论】:

标签: vba excel


【解决方案1】:

试试

Format$(Sheet1.Range("A1").Value,"yyyy-mm-dd")

尽管根据您的示例,您的代码中应该有一个 -FILENAME 位吗?

你想要

2018-03-06-FILENAME.txt

但只给:

currentPath & currentDate & ".txt"

所以,需要currentPath &amp; "-" &amp; currentDate &amp; "-" &amp; FILENAME &amp; ".txt"

假设 FILENAME 是一个变量。

【讨论】:

  • 我完全忘记在其中包含通配符!它应该是“*.txt”。这仍然有效,对吧?
  • 文件名是变量吗?您可以在 currentdate 之后使用通配符来查找,但不能用于打开。注意使用 Format$ 作为类型化函数更有效。如果有多个匹配项怎么办?
  • 你的意思是currentPath & "-" & currentDate & "-" & "*.txt"
  • 我不需要连字符。我现在有 currentPath & currentDate & "*.txt" 并且它有效。
  • 不用担心。我正在复制你给的字符串。
【解决方案2】:

currentDate = Sheet1.Range("A1").Value 确实会给出 Excel 用于存储日期的顺序日期 I.E.(43261)

请改用currentDate = Format(Sheet1.Range("A1").text, "YYYY-MM-DD") &amp; "FILENAME.txt"

您还可以通过使用debug.print currentdate 来检查变量中存储的内容,然后使用Ctrl+G 控制台在宏执行后显示打印值。

我强烈建议使用instr 函数来查找文件名中的日期,而不是直接比较它们,除非您的文件日期不是唯一的。还记得使用 TextCompare 模式进行不区分大小写的比较。

示例:If instr(1, CURRENT FILENAME STRING, currentDate, vbTextCompare) then 'if filename is found then code goes here. end if

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    相关资源
    最近更新 更多