How to read and output specific data in a VB file?

To read and output specified data, you can use the file reading function in VB to read all the data in the file, and use conditional statements to filter out the specified data and output it.

Here is a simple example demonstrating how to read all data from a text file and output lines containing specific keywords.

Sub ReadFile()
    Dim filePath As String
    Dim fileContent As String
    Dim keyword As String
    
    ' 设置文件路径和关键字
    filePath = "C:\path\to\file.txt"
    keyword = "指定数据"
    
    ' 打开文件并读取所有内容
    Open filePath For Input As #1
        fileContent = Input$(LOF(1), #1)
    Close #1
    
    ' 按行分割内容
    Dim lines() As String
    lines = Split(fileContent, vbCrLf)
    
    ' 遍历每一行并输出包含指定关键字的行
    Dim line As Variant
    For Each line In lines
        If InStr(1, line, keyword, vbTextCompare) > 0 Then
            Debug.Print line ' 输出到调试窗口
            ' 或者使用 MsgBox line 输出到消息框
        End If
    Next line
End Sub

In the example above, you need to set the filePath variable as the path of the file you want to read, and set the keyword variable as the keyword to filter. Then, open the file using the Open statement, read all the content of the file using the Input$ function, and finally close the file using the Close statement.

Next, use the Split function to divide the file content into a string array by lines. Then, use a For Each loop to iterate through each line, and use the InStr function to determine if the line contains a keyword. If it does, use the Debug.Print statement to output the line to the debug window, or use the MsgBox statement to output the line to a message box.

Please note that the above examples are only applicable for reading text files. Different methods may be required for reading other types of files.

bannerAds