首页 > 解决方案 > 如何计算文本文件字符串长度并在 VBA 中执行检查

问题描述

在一个文本文件中,我有很多行,每行都是一个字符串。我需要对每一行/字符串进行检查,直到找到一个长度超过 15 个字符的行/字符串。当它找到一个时,它应该显示一个MsgBox并结束循环。据了解,我需要使用 Do until EOF 循环,但无法进行检查。

Sub OpenFileAsText()
Dim FilePath As String

    FilePath = "C:\Users\Default\Desktop\test.csv"
    Open FilePath For Input As #1
    row_number = 0

        Loop Until EOF(1)
         Line Input #1, LineFromFile

        'cant work out the code to do the check

   row_number = row_number + 1
   Loop
   Close #1
End Sub

标签: vbams-word

解决方案


谢谢你的开始。这段代码可以满足我的需要。

Sub Sample()


    Dim filename As String
    filename = "C:\Users\Default\Desktop\339734.csv"

    Dim file As Integer
    file = FreeFile
    Open filename For Input As #file

    Dim rowNumber As Long
    rowNumber = 0

    Dim match As String
    Do Until EOF(file)
        rowNumber = rowNumber + 1

        Dim line As String
        Line Input #file, line

        If Len(line) > 15 Then
            match = line
            Exit Do
        End If
    Loop

    Close #file

    If match <> vbNullString Then
        MsgBox "Found"
    Else
        MsgBox "Did not find"
    End If
End Sub

推荐阅读