如何用vba实现查询文件里的字符串并把查询到的字符串所在文件的行数,在哪句列出出来,查询条件不写在代码里

解决方案 »

  1.   

    Input读取文件
    Instr查找字符串具体用法google下。
      

  2.   

    因为win10装不了vb6,所以用vbs写了个脚本,你可以参考一下:
    Set fso = createobject("scripting.filesystemobject")
    curdir = fso.getparentfoldername(wscript.scriptfullname)
    path = fso.buildpath(curdir,"test.txt")target = inputbox("请输入要查找的内容:")Set stream = fso.opentextfile(path,1,False)
    content = stream.readall
    stream.closearrLines = Split(content,vbcrlf)
    For i = lbound(arrlines) To ubound(arrlines)
    If InStr(arrlines(i),target) > 0 Then
    msgbox "第" & (i+1) & "行: " & arrlines(i)
    End If
    Nextmsgbox "查找完毕!"
      

  3.   

        Function TT(strb)
        Dim aa, bb, cc
        Dim strFile As String
        Dim intFile As Integer
        Dim strData As String
        strFile = "d:\1.txt"
        intFile = FreeFile
        Open strFile For Input As intFile
        stra = StrConv(InputB(FileLen(strFile), intFile), vbUnicode)
        Debug.Print stra
        Close intFile
        '--------------
        aa = InStr(1, stra, strb)
        bb = Mid(stra, 1, aa)
        cc = Len(Replace(bb, vbCrLf, ""))
        Debug.Print (aa - cc) \ 2 + 1
        TT = (aa - cc) \ 2 + 1
        End Function
      

  4.   

    Function TT(strb, path)
        Dim aa, bb, cc, intFile, strData
        intFile = FreeFile
        Open path For Input As intFile
        stra = StrConv(InputB(FileLen(path), intFile), vbUnicode)
        Close intFile
        aa = InStr(1, stra, strb)
        bb = Mid(stra, 1, aa)
        cc = Len(Replace(bb, vbCrLf, ""))
        TT = (aa - cc) \ 2 + 1
        End Function
      

  5.   


    'Search 函数 FilePath 文件的绝对路径 SearchStr 要查找的字符串
    '如果找到字符串,返回字符串所在位置,否则返回空字符串
    '至于文件绝对路径的正确与否,是否为空,自己去检查Public Function Search(FilePath As String, SearchStr As String) As String
        Dim StrData As String   '定义临时变量
        Dim Row As Integer  '定义行
        Dim Col As Integer  '定义列
        
        Open FilePath For Input As #1       '打开文件
        
        Do Until (EOF(1))   '直到循环(直到文件末尾)
            Row = Row + 1   '行计数+1
            Line Input #1, StrData  '一行一行读入临时变量
            
            If InStr(StrData, SearchStr) <> 0 Then  '如果找到字符串
                Col = InStr(StrData, SearchStr)     '将字符串所在位置赋值给Col
                Exit Do     '退出循环
            End If
        Loop
        
        If Col <> 0 Then     '如果找到字符串
            Search = CStr(Row) & "," & CStr(Col)    '以“行,列”的格式返回字符串所在位置,便于后期加工
        End If
        Close #1        '关闭文件
    End Function