【问题标题】:Excel VBA - search for a word in a text file and return true or false in excelExcel VBA - 在文本文件中搜索单词并在 excel 中返​​回 true 或 false
【发布时间】:2015-05-18 18:20:29
【问题描述】:

我有大约 200 个不同名称的文本文件存储在一个文件夹中。我想要的是找到特定单词时(例如错误,错误)。我希望excel在A列中的文本文件名旁边提及truefalse

Name        Error Found
Textfile1   TRUE
Textfile2   FALSE
Textfile3   TRUE
Textfile4   TRUE
Textfile5   TRUE
Textfile6   TRUE
Textfile7   TRUE
Textfile8   TRUE
Textfile9   TRUE
Textfile10  FALSE
Textfile11  FALSE
Textfile12  FALSE
Textfile13  FALSE
Textfile14  FALSE

【问题讨论】:

  • 您在执行此操作时遇到的确切问题是什么?
  • 欢迎来到 SO!阅读how to ask a good question 将帮助您更快地得到答案。请记住,这不是代码编写服务,因此请发布您所拥有的内容,我们可以帮助您修复它。如果您不知道从哪里开始,请尝试使用宏记录器。

标签: excel vba


【解决方案1】:

我很无聊,这段代码未经测试,远非完美。将其粘贴到新的代码模块中并调整常量以满足您的需要。

这可能根本不起作用,但可能会给你一些指导。

Public Const SearchPath = "C:\example\"
Public Const SearchTerm = "helloworld"

Sub Main()
Dim oFSO As Object: Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFolder As Object
Dim oFile As Object

Dim Sheet As Worksheet: Set Sheet = ThisWorkbook.Worksheets("Sheet1")
Dim Index As Integer: Index = 1
Dim Result As Boolean
Dim Search As String: Search = SearchTerm
' retreive a list of files
    Set oFolder = oFSO.getFolder(SearchPath)

    For Each oFile In oFolder.Files
        Sheet.Cells(Index, 1).Value2 = oFile.Name
        Index = Index + 1
    Next oFile

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

' process list of files
    Index = 1

    While Not Sheet.Cells(Index, 1).Value2 = ""
        Result = Process(SearchPath & Sheet.Cells(Index, 1), Search) ' only the filename was being passed, added the parent folder from the constant above
        If Result = True Then
            Sheet.Cells(Index, 2).Value2 = "TRUE"
        Else
            Sheet.Cells(Index, 2).Value2 = "FALSE"
        End If
        Index = Index + 1
    Wend
End Sub

Public Function Process(ByVal File As String, ByVal Search As String) As Boolean
Dim Result As Boolean: Result = False
Dim FileNumber As Integer: FileNumber = FreeFile()
Dim Data As String

    Open File For Input As #FileNumber
    While Not EOF(FileNumber)
        Line Input #FileNumber, Data
        If InStr(1, Search, Data) > 0 Then
            Result = True
            GoTo BOut
        End If
    Wend
BOut: ' I used the wrong syntax for goto statements here
    Close #FileNumber
    Process = Result

End Function

【讨论】:

  • 返回错误:(无法通过函数
  • @AslamRasheed - 我现在已经修复了代码中的一些小错误。
  • 嗨 NickSlash 你已经解决了我的部分问题。太棒了..我能够将所有文件列出到excel中..我的意思是所有文件的名称都会出现......但是在“打开文件以输入为#FileNumber”这一行仍然有一个错误,它的值为1然后什么都没有发生......
  • 代码对我来说没有问题。请确保我的示例顶部的 SearchPath 常量以斜杠结尾。这是我能想到的唯一可能导致问题的原因。
猜你喜欢
  • 2023-02-22
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2018-05-05
  • 2018-07-13
  • 1970-01-01
相关资源
最近更新 更多