简体   繁体   中英

If cell contains specific text then move to a new workbook

I have a large dataset with the first column being the variable ClientNames. Some ClientNames have the word "Project" in and I'd like to use VBA to find and select each of the ClientNames which have the word "Project" in and move the entire row for these clients into a new workbook (one workbook with all the clients that have "project" in their ClientName. How can I do this?

You can achieve that by using the below VBA code, the below code searches for text "project" in the first columns and then shifts the entire row to new workbook called Project

Option Explicit

Sub project()

Dim lastrow As Long
Dim count As Long
Dim sht As Worksheet
Set sht = ActiveSheet

Dim dst As Workbook
Set dst = Workbooks.Add
dst.SaveAs Filename:="Project"
dst.Sheets.Add.Name = "Project"
count = 1

sht.Activate
lastrow = sht.Cells(Rows.count, 1).End(xlUp).Row
Dim i As Long
    For i = 1 To lastrow
    
        If InStr(1, sht.Cells(i, 1).Value, "Project", vbTextCompare) > 0 Then
        sht.Rows(i).Cut
        dst.Sheets("Project").Rows(count).Insert Shift:=xlDown
        sht.Rows(i).Delete
        count = count + 1
        i = i - 1
        End If
    
    Next i
 End Sub

You can use InStr function to know if "Project" is in your cell. Then you can use entirerow to select your row then copy it to the destination sheet and finally delete the row from source sheet.
Be careful of your line index which will be need to be updated after deleting your row

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