【问题标题】:Read file without opening and delete it在不打开的情况下读取文件并将其删除
【发布时间】:2015-07-08 09:41:05
【问题描述】:

我正在尝试找出一种方法,可以在不打开文件的情况下通过 excel VBA 读取 .txt 中的第一行文本,因为我看到的所有示例都涉及打开文件,所以我一直很难找到.txt 一种或另一种方式。

除此之外,我想知道是否有任何方法可以让 VBA 代码在 excel 关闭后的一段时间内删除提到的 .txt ......我不太确定这是否可能(至少使用 VBA)。

编辑:

简化后的代码如下:

Option Explicit
Public g_strVar As String
Sub Test_Proc()
    Dim row as Long        
    row = 2

    Do While Cells(row, 1) <> "" 
        Cells(row, 2) = ImportVariable(Cells(row, 1))
        row = row + 1
    Loop

End Sub
Function ImportVariable(strFile As String) As String

    Open strFile For Input As #1
    Line Input #1, ImportVariable
    Close #1

End Function

第 1 列包含每个 .txt 文件的位置,在它旁边的列中,我必须详细说明每个文件的第一行文本是什么。问题是该列表有几次大约 10K 长,我能想到的唯一可以改进执行时间的地方是“打开/关闭”,因为其中一些 .txt 文件大小为 12.000 KB,需要一点时间才能打开。

【问题讨论】:

  • 如果 VBA 已关闭,您将无法在 Excel 中运行它。您也许可以通过计划任务使用 VBScript。为什么无法打开文本文件?
  • @Rory 因为我想循环遍历许多文件,而打开/关闭每个文件所花费的时间最终会累积成浪费的分钟数。由于我不想编辑数据而只是提取它,我想知道是否可以这样做而无需打开它。
  • 不打开文件就无法从逻辑上读取文件;也许如果您分享您的阅读代码并解释为什么删除文件会有助于改进,可以提出建议
  • @AlexK。编辑了条目并添加了我的代码的简化版本(在将文本输入 excel 时要考虑很多变量)。
  • 我会尝试循环加载文本到数组中的文件,然后在工作表上执行 single 更新:Range("B1:B" &amp; row).Value = Application.Transpose(arry) 因为每次更新工作表都会消耗一些时间文件

标签: vba excel


【解决方案1】:

这可能比打开每个文件更快(在 0.1953125 秒内从 18.5 Mb 文件中读取第一行)


Option Explicit

Dim cmdLine As Object

Sub Test_Proc()
    Dim i As Long, minRow As Long, maxRow As Long, rng1 As Range, rng2 As Range
    Dim t As Double, ws As Worksheet, x As Variant, col1 As Variant, col2 As Variant

    Set ws = ThisWorkbook.Worksheets(1)
    minRow = 2
    With ws
        .Columns(2).Delete
        maxRow = .UsedRange.Rows.Count
        Set rng1 = .Range("A1:A" & maxRow)
        Set rng2 = .Range("B1:B" & maxRow)
    End With
    col1 = rng1.Value2: col2 = rng2.Value2
    Set cmdLine = CreateObject("WScript.Shell")

    Application.ScreenUpdating = False
    t = Timer
    For i = minRow To maxRow
        If Len(col1(i, 1)) > 0 Then
            ws.Cells(i, 2).Value2 = Replace(ImportLine(col1(i, 1)), vbCrLf, vbNullString)
        End If
    Next
    'rng2.Value2 = col2
    Application.ScreenUpdating = True
    InputBox "Duration: ", "Duration", Timer - t    '18.5 Mb file in 0.1953125 sec
End Sub

Function ImportLine(ByVal strFile As String) As String
    ImportLine = Replace(cmdLine.Exec( _
            "%comspec% /C FindStr /N . " & strFile & " | FindStr ^1:" _
        ).STDOut.ReadAll, "1:", vbNullString)
End Function

有点嵌套,但它执行以下操作:

  • CMD /C - 打开命令行窗口,完成后将其关闭
  • FindStr /N 。 C:\test.txt - 查找任意字符,输出行号为“1:”的行
  • | FindStr ^1: - 重定向到另一个 FindStr,它使用正则表达式在行首查找“1:”
  • 命令行完成后,将输出返回到 Replace 函数
  • 替换删除“1:”并返回字符串

如果您的文件可能在第一行的其他位置包含字符串“1:”

  • 我们可以使用 Right() 函数:return Right(output, Len(output)-2)
  • 或者我们可以使用不同的命令行,用“[1]”对行进行编号:

    • 查找 /N " " C:\test.txt |查找“[1]”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2021-08-23
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2010-11-04
    相关资源
    最近更新 更多