以下是一个使用 VBA 运行 findstr 命令来查找当前目录下文件中是否包含 "happy" 字符并将输出内容输出到 Sheet1 的示例代码:

Sub RunFindstr()
    Dim cmd As String
    Dim tempFile As String
    Dim output As String
    Dim i As Integer
    
    ' 创建一个临时文件来保存 findstr 命令的输出
    tempFile = Environ("TEMP") & "\findstr_output.txt"

    ' 构建 findstr 命令
    cmd = "cmd /c findstr /s /i /m ""happy"" * > " & tempFile
    
    ' 运行 findstr 命令
    Shell cmd, vbHide
    
    ' 等待一会儿,确保 findstr 命令执行完毕
    Application.Wait Now + TimeValue("00:00:02")
    
    ' 读取 findstr 命令的输出
    output = ReadFileContent(tempFile)
    
    ' 将输出内容写入 Sheet1 的第一列
    Sheets("Sheet1").Activate
    Range("A1").Activate
    ActiveCell.Value = output
    
    ' 删除临时文件
    Kill tempFile
End Sub

Function ReadFileContent(filePath As String) As String
    Dim fileNumber As Integer
    Dim fileContent As String
    
    fileNumber = FreeFile
    
    ' 打开文件并读取内容
    Open filePath For Input As #fileNumber
    fileContent = Input$(LOF(fileNumber), fileNumber)
    Close #fileNumber
    
    ReadFileContent = fileContent
End Function

请确保在运行此代码之前,已经在 Excel 中创建了名为 "Sheet1" 的工作表。运行 RunFindstr() 子过程后,它将在 Sheet1 的第一列中输出 findstr 命令的结果

vba运行 findstr命令查找当前目录下文件中是否包含happy字符并且输出打印输出内容到shee1中

原文地址: https://www.cveoy.top/t/topic/ipuv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录