简体   繁体   中英

Excel: search for a word in the column and copy it to another column on the same sheet

I have an excel table with rows of data. The column J contains various descriptions of goods. I need to search all the rows in this column for the word LATEX and when it is found, copy ONLY this word to the column A on the same sheet on the same row. I was trying to find a solution and came up with this macro using Autofilter, but it is not working properly. Can you please help me?

Sub FilterAndCopy()

    Dim dataWs As Worksheet
    Dim copyWs As Worksheet
    Dim totRows As Long
    Dim lastRow As Long

    Set dataWs = Worksheets("Massiv")
    Set copyWs = Worksheets("Massiv")

    With dataWs
        .AutoFilterMode = False
        With .Range("J:J")
             .AutoFilter Field:=1, Criteria1:="LATEX"
        End With
    End With

    totRows = dataWs.Range("J:J").Rows.count
    lastRow = dataWs.Range("J" & totRows).End(xlUp).Row
    dataWs.Range("J:J" & lastRow).Copy
    copyWs.Range("A6").PasteSpecial Paste:=xlPasteValues
    dataWs.AutoFilterMode = False

With the following changes, your code should work. I've noted the changes in the comments in the code.

With dataWs
    .AutoFilterMode = False
    With .Range("J:J")
         'Use wildcard to search for word LATEX within contents of column J cells 
         .AutoFilter Field:=1, Criteria1:="*LATEX*"
    End With
End With

totRows = dataWs.Range("J:J").Rows.Count
lastRow = dataWs.Range("J" & totRows).End(xlUp).Row
'After filtering, select the visible cells in column A...
Set rng = dataWs.Range("A2:A" & lastRow).SpecialCells(xlCellTypeVisible)
'... and set their values to "LATEX"
rng.Value = "LATEX"
dataWs.AutoFilterMode = False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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