计算文本文件中的行数时的错误代码52

问题描述 投票:0回答:2

我正在编写一个代码来通过VBA打开文本文件,并匹配记事本中从excel获取的mail_id的值。我看到了很少的示例代码,并根据我的数据和要求对其进行了修改,但在计算代码的行数时,它显示的是错误编号52.另外,请告诉我如何搜索字符串在记事本中,如果字符串匹配,则复制它下面的文本。请参考以下代码以供参考:

 If mail_id <> " " Then

      Dim fso As Object
      Dim sfile As String


      Set fso = CreateObject("shell.application")
      sfile = "C:\My Documents\Textfile.txt"
      fso.Open (sfile)
       f = FreeFile
         Do While Not EOF(f)
            Ingline = Ingline + 1
            Line Input #f, strLine
            If InStr(1, strLine, mail_id, vbBinaryCompare) > 0 Then
            MsgBox Ingline, vbInformation
            bInfound = True
            End If
            Exit Do
          'End If
      Loop
      Close #f
      If Not blnFound Then
           MsgBox "Search string not found", vbInformation
       End If

它显示了Do While Not EOF时的错误(f)

vba excel-vba excel
2个回答
1
投票

我认为你混合了不同的方法如何在VBA中打开文本文件:

这应该打开一个文件并逐行读取:

Option Explicit

Public Sub ReadLineByLineFromTextFile()
    Const ForReading = 1, ForWriting = 2, ForAppending = 8

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim FileName As String
    FileName = "c:\temp\test.txt"

    Dim MyFile As Object
    Set MyFile = fso.OpenTextFile(FileName, ForReading)

    '' Read from the file line by line
    Do While MyFile.AtEndOfStream <> True
        Dim TextLine As String
        TextLine = MyFile.ReadLine

        '' Do stuff to TextLine here like …
        'If InStr(1, TextLine, mail_id, vbBinaryCompare) > 0 Then
        '    MsgBox "found", vbInformation
        '
        '    Exit Do 'cancel loop when found
        'End If

    Loop
    MyFile.Close
End Sub

0
投票

您正在混合两种不同的方式来读取VBA中的文本文件。两者都在SO上的同一个问题中解释。

a)使用openhttps://stackoverflow.com/a/11528932/7599798

b)使用FileSystemObjecthttps://stackoverflow.com/a/11529980/7599798

© www.soinside.com 2019 - 2024. All rights reserved.