vba如何搜索单词然后添加具有特定术语的列?

时间:2018-06-14 15:04:32

标签: vba excel-vba excel

我目前正试图找到一种方法来搜索短语" term"在专栏" B"然后添加一些文字"新文字"在一个新专栏" I"。我是VBA的新手,我目前没有添加任何文字的代码:

    Sub addclm()

Dim row As Long
Dim column As Long
Dim strsearch As String
Dim rfind As Range
Dim sfirstaddress As String

strsearch = "term"
row = Sheet4.Range("I4").row
column = Sheet4.Range("I4").column


With Sheet4.Columns("B:B")
    Set rfind = .Find(strsearch, LookIn:=xlValues, LookAt:=xlPart, SearchDirection:=xlNext, MatchCase:=False)

If Not rfind Is Nothing Then
sfirstaddress = rfind.Address
Sheet1.Cells(row, column) = "new text"
row = row + 1


End If
End With
End Sub

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

有点不清楚你想要做什么,但考虑到你提供的信息,这是我对你想要的最好的猜测。将其粘贴到模块中,而不是工作表中。

  1. 确定要扫描的范围(Sheet4,ColB,最后使用的单元格到B2)
  2. 遍历每个Cell寻找" term"
  3. 如果找到,请转到sheet1,粘贴值"新文本"对应的ROW
  4. 如果找不到,请不要做任何事
  5. 循环2-4,直到涵盖所有范围

    Option Explicit
    Sub addclm()
    
    Dim WB As Workbook
    Set WB = ThisWorkbook
    
    Dim strsearch As String
    strsearch = "term" 'what to search for in each cell in B
    
    Dim LRow As Long 'Determine the last row in B to limit loop
    LRow = WB.Sheets("Sheet4").Range("B" & WB.Sheets("Sheet4").Rows.Count).End(xlUp).row
    
    Dim MyCell As Range
    Dim MyRange As Range
    Set MyRange = WB.Sheets("Sheet4").Range("B2:B" & LRow) 'Where to loop (From bottom last row to B2)
    
    For Each MyCell In MyRange
        If InStr(MyCell.Text, strsearch) > 0 Then
            WB.Sheets("Sheet1").Range("I" & MyCell.row) = "new text"
        End If
    Next MyCell    
    End Sub