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

时间:2018-03-05 14:42:56

标签: vba excel-vba excel

我正在编写一个代码来通过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)

时的错误

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

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