读取文件而不打开并删除它

我试图找出一种方法来通过Excel VBA读取.txt中的第一行文本,而无需打开该文件,因为我看过的所有示例都涉及打开.txt文件这样或那样。

除此之外,我想知道是否有任何方式让我得到的VBA代码删除提及的.txt一段时间后,Excel已closures…我不太确定,甚至是远程可能的(与VBA至less)。

编辑:

简化的代码如下所示:

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的长度,而且我可以从这个地方改进的唯一的地方就是在“打开/closures”的时候,因为其中的一些.txt文件是12.000 KB大小,需要一点点打开。

这可能比打开每个文件更快(在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 – 打开一个命令行窗口,完成后closures它
  • FindStr / N。 C:\ test.txt – 查找任何字符,并输出格式为“1:”的行号
  • | FindStr ^ 1: – redirect到另一个使用正则expression式在行首find“1:”的FindStr
  • 当命令行完成时,将输出返回到Replace函数
  • replace删除“1:”并返回string

如果您的文件可能在第一行的其他地方包含string“1:”

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

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