简体   繁体   English

使用 VBA 在 Excel 中查找关键字

[英]Finding key words in Excel with VBA

The file I am working on is picking the selected words from all the comments, colors them and segregates them into the dedicated tabs.我正在处理的文件是从所有评论中选择选定的单词,为它们着色并将它们隔离到专用选项卡中。

All keywords have been coded into the macro itself.所有关键字都已编码到宏本身中。 Instead of writing the keywords to the macro, I want to tell the macro the keywords are located in an array in an excel sheet so everybody can use the file according to their needs.我不想将关键字写入宏,而是告诉宏关键字位于 Excel 工作表中的数组中,以便每个人都可以根据需要使用该文件。

When I made below changes for keywords to an array, I am getting below error on the screenshot that I do not know why.当我对数组的关键字进行以下更改时,我在屏幕截图上遇到错误,我不知道为什么。

Satellite:卫星:

KeyW = Array("Satellite", "image", "blacks out", "resolution")

Satellite:卫星:

KeyW = Array(Worksheets("MAIN").Range("N5:N15"))

The code below was not written by me.下面的代码不是我写的。 I just made some modifications.我只是做了一些修改。

Error that I am getting:我得到的错误:

runtime error 13, Type mismatch运行时错误 13,类型不匹配

when I click debug it shows this yellow line当我点击调试它显示这条黄线

    Sub sort()
   
   Dim KeyW()
   Dim cnt_Rows As Long, cnt_Columns As Long, curr_Row As Long, i As Long, x As Long

   Application.Calculation = xlCalculationManual

   Application.ScreenUpdating = False
   
   

    Sheets(Array("Television", "Satellite", "News", "Sports", "Movies", "Key2", "Key3", "Error", "Commercial", "Key4", "TV", "Key5", "Key6", "Signal", "Key1", "Key7", "Design", "Hardware")).Select


  
Satellite:
   
   KeyW = Array("Satellite", "image", "blacks out", "resolution")
   
   KeyWLen = UBound(KeyW, 1)

   j = 2

   For i = 0 To KeyWLen

         With Worksheets(1).Range("c4:e7000")
         Set c = .Find(KeyW(i), LookIn:=xlValues, LookAt:=xlPart)
         If Not c Is Nothing Then
            firstAddress = c.Address
            Do
               Sheets("Satellite").Range("b" & j).Value = Worksheets(1).Range("a" & c.Row).Value
               Worksheets(1).Range(c.Address).Copy
               Sheets("Satellite").Activate
               Range("a" & j).Select
               Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
                  , SkipBlanks:=False, Transpose:=False
                  
               Range("a" & j).Select
               WordPos = 1
               StartPos = 1
               SearchStr = KeyW(i)
               While WordPos <> 0
                  WordPos = InStr(StartPos + 1, Range("a" & j).Value, SearchStr, 1)
                  If WordPos > 0 _
                  Then
                     With ActiveCell.Characters(Start:=WordPos, Length:=Len(SearchStr)).Font
                          .FontStyle = "Bold"
                          .Color = -16727809
                     End With
                     StartPos = WordPos
                  End If
               Wend
               
               Worksheets(1).Activate
               j = j + 1
               Set c = .FindNext(c)
            Loop While Not c Is Nothing And c.Address <> firstAddress
         End If
      End With
   Next i

I'd start by splitting out some of the logic into standalone methods, and calling them from your main code: this makes it easier to see what's going on and allows some re-use of your code later on.我首先将一些逻辑拆分为独立的方法,然后从您的主代码中调用它们:这样可以更容易地查看正在发生的事情,并允许稍后重用您的代码。

For example:例如:

Sub sort()
    
    Dim wb As Workbook
    Dim txt As String, allCells As Collection, c As Range, w As Range, rngDest As Range

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
   
    Set wb = ThisWorkbook
    
    '(removed sheet selection code - not needed here)

    Set rngDest = wb.Worksheets("Satellite").Range("A2") 'start listing matches here
    
    For Each w In wb.Worksheets("MAIN").Range("N5:N15").Cells 'loop over possible search terms
        txt = Trim(w.Value)
        If Len(txt) > 0 Then
            Set allCells = FindAll(wb.Worksheets(1).Range("c4:e7000"), txt) 'get all matches
            For Each c In allCells
                c.Copy rngDest                      'copy matched cell
                BoldWord rngDest, txt               'bold matched text
                rngDest.Offset(0, 1) = _
                  c.EntireRow.Columns("A").Value    'copy colA from matched cell
                Set rngDest = rngDest.Offset(1)     'next result row
            Next c
        End If
    Next w
    
End Sub

'return a Collection of all cells in `rng` which contain `txt`
Public Function FindAll(rng As Range, txt As String) As Collection
    Dim rv As New Collection, f As Range
    Dim addr As String
 
    Set f = rng.Find(what:=txt, after:=rng.Cells(rng.Cells.Count), _
        LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False)
    If Not f Is Nothing Then addr = f.Address()
    
    Do Until f Is Nothing
        rv.Add f
        Set f = rng.FindNext(after:=f)
        If f.Address() = addr Then Exit Do
    Loop
    Set FindAll = rv
End Function

'Bold all instances of `wrd` in cell `c`
Sub BoldWord(c As Range, txt As String)
    Dim pos As Long, start As Long
    start = 1
    Do
        pos = InStr(start, c.Value, txt, vbTextCompare)
        If pos = 0 Then Exit Do
        With c.Characters(pos, Len(txt))
            .Font.Bold = True
            .Font.Color = vbRed
        End With
        start = pos + Len(txt)
    Loop
End Sub

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

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