a little understanding before i explain what this code is about, first the user will open a empty microsoft excel, and then the user will on a macro to open multiple workbook into the current active excel, for example, if the user chose to open "book1" and "book2" together, the current active excel will open them and split them into a new sheet named after the workbook it was currently named, example sheet "book1" and sheet "book2".
so basically this program enables user to search for a string(in all the sheets), and then after finding out where the string is, it copies the entire row + header to a new sheet named after the searching string.
For example, if i search for apple, it will copy the entire row consists of the word " apple " and paste into a new sheet named "apple" and the row and header will be copied over there, what i need to do now is to create a new workbook and create a new sheet named after the search string AND the workbook it was previously named.
Like i said, i've opened workbook "book1" and "book2", and if the searched word is from sheet "book1", the macro will copy the searched string into a new workbook, a new sheet named "book1" with the information.
i know i had explained this in a very wordy way, let me know if you need any clarification.
Private Sub CommandButton5_Click()
Dim i As Long, nRowsAddePerSheet As Long, nRows As Long, _
nRowsMax As Long, nSheets As Long
Dim strSearch, strSearch2
Dim rg As Range, rgF As Range
Dim wks
Dim x
strSearch = Application.InputBox("Please enter the search string")
strSearch2 = Replace(strSearch, "*", "")
If Len(strSearch2) <= 0 Then
MsgBox "ABandon: Search string must not be empty."
Exit Sub
End If
Application.ScreenUpdating = False
nSheets = Sheets.Count
nRowsMax = ActiveSheet.Rows.Count
For x = 1 To nSheets
On Error Resume Next
Set wks = Worksheets(strSearch2)
If (Err) Then
Set wks = Worksheets.Add(After:=Sheets(Sheets.Count))
wks.Name = strSearch2
Err.Clear
End If
On Error GoTo 0
Sheets(x).Activate
Set rg = ActiveSheet.Cells(1).CurrentRegion
nRows = rg.Rows.Count
nRowsAddePerSheet = 0
For i = 1 To nRows
Set rgF = rg.Rows(i).Find(strSearch, , xlValues, xlWhole)
If Not rgF Is Nothing Then
If (nRowsAddePerSheet <= 0) Then
If (i <> 1) Then
rg.Rows(1).Copy wks.Range("A" & nRowsMax).End(xlUp).Offset(1, 0)
End If
End If
rg.Rows(i).Copy wks.Range("A" & nRowsMax).End(xlUp).Offset(1, 0)
nRowsAddePerSheet = nRowsAddePerSheet + 1
End If
Next
Next
Set rgF = Nothing
Set rg = Nothing
Set wks = Nothing
Application.ScreenUpdating = True
End Sub
apple
? anywhere in the worksheet or a particular column? – Siddharth Rout