繁体   English   中英

如何使用 Excel vba 查找特定文本单词

[英]How to Find specific text word using Excel vba

我需要从 Excel 文件中查找特定单词。 我想逐行搜索,如果找到单词,向下跳过 2 行并复制接下来的 20 行并循环到下一个单词。

Sub Example4()

Dim FilePath As Workbook    
Dim wsheet As Worksheet
Dim i, lcount, lcount2 As Integer
 Dim cell, rgFound As Range
Dim Found As Range, LastRow As Long


 Set FilePath = Workbooks.Open("D:\SLC.txt")
  Dim rowVal As Integer
    rowVal = 1

    For lcount = 1 To FilePath.Sheets("SLC").Range("A1048576").End(xlUp).Row

    Set rgFound = Range("A1:A1048576").Find("TXN. NO     TXN SEQ", ThisWorkbook.Sheets(), Cells(rowVal, 1))


            FilePath.Cells(wsheet.Range(rowVal).End(xlDown).Row + 3).xlCopy

            wbook2.Worksheets(1).Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
            wbook2.SaveAs ("D:\SLC_Copied.xlsx")
            wbook2.Close

   rowVal = rgFound1.Row

   Debug.Print lcount
   Next lcount


End Sub

正如 Siddharth Rout 建议的那样,使用 Find 和 FindNext。 尝试选择适合其类型的变量名称,调用工作簿对象 FilePath 会让其他试图理解您的脚本的人感到困惑。

Option Explicit
Sub Example4()

    Const TEXT = "TXN. NO     TXN SEQ"
    Const TEXT_FILENAME = "D:\SLC.txt"
    Const OUT_FILENAME = "D:\SLC_Copied.xlsx"

    Dim wbText As Workbook, wbOut As Workbook, rngOut As Range
    Dim wsText As Worksheet, wsOut As Worksheet, count As Integer
    Dim rngSearch As Range, rngFound As Range, rowFirstFind As Long

    ' open text file no link update, read only
    Set wbText = Workbooks.Open(TEXT_FILENAME, False, True)
    Set wsText = wbText.Sheets(1)

    ' search
    Set rngSearch = wsText.Columns("A:A")
    Set rngFound = rngSearch.Find(what:=TEXT, LookIn:=xlValues, LookAt:=xlPart)

    If rngFound Is Nothing Then
        wbText.Close
        MsgBox "No lines match [" & TEXT & "]", vbCritical, "Exiting Sub"
        Exit Sub
    Else

        ' create new workbook for results
        Set wbOut = Workbooks.Add
        Set wsOut = wbOut.Sheets(1)
        Set rngOut = wsOut.Range("A1")
        rowFirstFind = rngFound.Row

        Do
            'Debug.Print rngFound.Row
            rngFound.Offset(3, 0).Resize(20, 1).Copy rngOut
            Set rngOut = rngOut.Offset(20, 0)
            Set rngFound = rngSearch.FindNext(rngFound)
            count = count + 1
        Loop Until rngFound.Row = rowFirstFind

    End If
    wbText.Close False

    wbOut.SaveAs OUT_FILENAME
    MsgBox count & " blocks copied to " & wbOut.Name, vbInformation, "Finished"
    wbOut.Close

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM