How to find a string in several opened workbooks and color the row. String can be duplicate in every sheet and can appear in Column A, B or C. Can this code be adapted for more workbooks?
I found this code for one workbook:
Sub Search_String()
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim Escolhe_Cor As Long
Dim FirstFound As String
Dim sh As Worksheet
' Set Search value
SearchString = InputBox("Digite o número a ser procurado")
Escolhe_Cor = InputBox("Escolha uma cor para destacar esse número. De 3 a 56")
Application.FindFormat.Clear
' loop through all sheets
For Each sh In ActiveWorkbook.Worksheets
' Find first instance on sheet
Set cl = sh.Cells.Find(What:=SearchString, _
After:=sh.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not cl Is Nothing Then
' if found, remember location
FirstFound = cl.Address
' format found cell
Do
cl.EntireRow.Font.Bold = True
cl.EntireRow.Interior.ColorIndex = Escolhe_Cor
' find next instance
Set cl = sh.Cells.FindNext(After:=cl)
' repeat until back where we started
Loop Until FirstFound = cl.Address
End If
Next
End Sub
What the information you provided, it looks like you just need to add you current code to a loop. This will look at every open workbook, so if you don't want to apply this to all of them, a regular expression to identify the workbook name could be used.
For Each wb In Workbooks
'If you only want certain open workbooks searched use this If statement:
If wb.name = *criteria* Then
wb.Activate
'run your code that loops through each sheet
End If
Next wb
Related
I want to copy and paste from one excel to another using copy and paste visible cells only as I have a filtered table between a set range.
I'd like to do this through save CSV but apparently this is not possible. The code below works but it doesn't seem to copy paste visible cells/filtered cells like I'd like.
Thanks in advance. Or if there's another recommended way for getting filtered tables to a CSV I'd love to hear how. Cheers.
Sub Macro2()
'
' Macro2 Macro
'
'
Dim lastRow As Long
Dim ws As Worksheet, tbl As ListObject
Set ws = Sheets("Sheet1")
Set tbl = ws.ListObjects("Table1")
With tbl.ListColumns(3).Range
lastRow = .Find(What:="*", _
After:=.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End With
Sheet1.Range("A2").SpecialCells(xlCellTypeVisible).Copy _
Destination:=Range("A2")
ActiveWorkbook.SaveAs Filename:="C:\Users\teaz\Videos\CSV", FileFormat:= _
xlCSV, CreateBackup:=False
ActiveWorkbook.SaveCopyAs Filename:="C:\Users\teaz\Videos" & Test1Str & " " & TestStr & " " & ActiveWorkbook.Name
Application.ActiveWindow.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False
End Sub
Copy all previously filtered data from all worksheets to another
Sub CopyFilteredDataToNewWorkbook()
Dim newBook As Excel.Workbook
Dim rng As Excel.Range
Dim sht As Excel.Worksheet
Dim rowoffsetcount As Long
Dim newsht As Excel.Worksheet
Set newBook = Workbooks.Add
' ThisWorkbook.Worksheets is the same as the Sheets or Worksheets object, but more explicit
For Each sht In ThisWorkbook.Worksheets
' Get the used rows and columns
Set rng = sht.UsedRange
' Offset the range so it starts at row 15
rowoffsetcount = 15 - rng.Row
Set rng = rng.Offset(rowoffsetcount)
' Check there will be something to copy
If (rng.Rows.Count - rowoffsetcount > 0) Then
' Reduce the number of rows in the range so it ends at the same row
Set rng = rng.Resize(rng.Rows.Count - rowoffsetcount)
' Check that there is a sheet we can copy it to
On Error Resume Next
Set newsht = Nothing
Set newsht = newBook.Worksheets(sht.Index)
On Error GoTo 0
' We have run out of sheets, add another at the end
If (newsht Is Nothing) Then
Set newsht = newBook.Sheets.Add(, newBook.Worksheets(newBook.Worksheets.Count))
End If
' Give it the same name
newsht.Name = sht.Name
' Get the range of visible (i.e. unfiltered) rows
' (can't do this before the range resize as that doesn't work on disjoint ranges)
Set rng = rng.SpecialCells(xlCellTypeVisible)
' Paste the visible data into the new sheet
rng.Copy newsht.Range("A1")
End If
Next
End Sub
I think this line is your problem:
'/* you only worked on Range("A2") */
Sheet1.Range("A2").SpecialCells(xlCellTypeVisible).Copy
You should access your tbl object like:
'/* this will give you the entire filtered table body */
tbl.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy
Similarly, you can use:
Sheet1.Range("YourTableName").SpecialCells(xlCellTypeVisible).Copy
And lastly, avoid all objects with Active prefix (e.g. ActiveWorkbook, ActiveWindow). You already know how to assign variables, then be consistent about it.
I am a rookie to VBA coding and I'm working on a project to search a string (e.g. 1207_Stackoverflow_com) from all worksheet of a workbook lets call it WB1 and select the column which the code searches and paste it to another workbook say WB2. Every time the code searches the row containing the string will copy the column to the next sheet in WB2. I tried but code is giving an error. All help is appreciated. Below is the code which I construct (I know it is a crude code, feel free to use your style of coding to educate me)
Sub SearchAndPaste()
Dim WB1 As Workbook, WB2 As Workbook
Dim myRng As Variant, mFind As Variant
Dim rng As Range
Dim Col1
Set WB1 = Workbooks.Open("Path of workbook")
WB2 = ThisWorkbook
mDate = WB2.Sheets("Sheet1").Range("J3").Value
Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1")
Set rng = WB2.Worksheets.Range("A2:CJ2")
Cells(myRng.Row, myRng.Column).Select
Col1 = Selection.Column
For Each sh In ActiveWorkbook.Worksheets
' Find first instance on sheet
Set myRng = rng.Find(What:=Str(mFind), After:=sh.Cells(1, 1), _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not cl Is Nothing Then
' if found, remember location
Cells(myRng.Row, myRng.Column).Select
Col1 = Selection.Column
' Copy column
Do
' find next instance
Set Col1 = sh.Cells.FindNext(After:=cl)
' repeat until back where we started
Loop Until FirstFound = Col1.Address
End If
Next
End Sub
I have maintained two Excel reports EPC1.xlsx and Control Power Transformers.xlsm respectively.
I want to trigger an button click from Control Power Transformers.xlsm report where it will search for "CTPT" term in "A" column from EPC1.xlsx, once it finds the term it need to copy Column B and Column c till the row ends (in EPC1.xlsx) and paste it in Control Power Transformers.xlsm workbook
I am successful in retrieving the cell address of "CTPT" term but how to select the data from adjacent column B and C?
And this is what I have tried
Private Sub CommandButton23_Click()
Dim rngX As Range
Dim num As String
Windows("EPC 1.xlsx").Activate
Set rngX = Worksheets("Sheet1").Range("A1:A10000").Find("CTPT", Lookat:=xlPart)
num = rngX.Address ' Here we will the get the cell address of CTPT ($A$14)
Range(rngX, Range("C" & rngX.Row).End(xlDown)).Copy
Windows("Control Power Transformers.xlsm").Activate
Sheets("Sheet2").Select
ActiveSheet.Range("E2").PasteSpecial (xlPasteValues)
End Sub
Paste the below in sample workbook. The below code will help to select both files using file dialog. It will search for word "CTPT". if so it will copy the column values from CTPT sheet to control file.
Sub DetailsFilePath()
Dim File1 As String
Dim File2 As String
Dim findtext As String
Dim copyvalues As Long
Dim c As Variant
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
MsgBox "Open the CTPT file"
Application.FileDialog(msoFileDialogFilePicker).Show
'On Error Resume Next
' open the file
File1 = Application.FileDialog(msoFileDialogFilePicker).SelectedItems(1)
MsgBox "Open the Control Power Transformers file"
Application.FileDialog(msoFileDialogFilePicker).Show
File2 = Application.FileDialog(msoFileDialogFilePicker).SelectedItems(1)
Set wb1 = Workbooks.Open(Filename:=File1)
Set ws1 = wb1.Worksheets("sheet1")
Set wb2 = Workbooks.Open(Filename:=File2)
Set ws2 = wb2.Worksheets("sheet1")
findtext = "CTPT"
With ws1.Columns(1)
Set c = .Find(findtext, LookIn:=xlValues)
If Not c Is Nothing Then
copyvalues = c.Column
ws2.Columns(2).Value = ws1.Columns(2).Value
ws2.Columns(3).Value = ws1.Columns(3).Value
End If
End With
wb1.Close savechanges:=True
wb2.Close savechanges:=True
End Sub
You need to use FindNext to find other results, and the Offset will help you select what you want from the address of your results :
Sub test_Karthik()
Dim WbEPC As Workbook, _
WbCPT As Workbook, _
WsEPC As Worksheet, _
WsCPT As Worksheet, _
FirstAddress As String, _
WriteRow As Long, _
cF As Range, _
num As String
Set WbEPC = Workbooks("EPC 1.xlsx")
Set WbCPT = Workbooks("Control Power Transformers.xlsm")
Set WsEPC = WbEPC.Sheets("Sheet1")
Set WsCPT = WbCPT.Sheets("Sheet2")
With WsEPC
.Activate
With .Range("A1:A10000")
'First, define properly the Find method
Set cF = .Find(What:="CTPT", _
After:=ActiveCell, _
LookIn:=xlValues, _
Lookat:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
'If there is a result, keep looking with FindNext method
If Not cF Is Nothing Then
FirstAddress = cF.Address
Do
num = cF.Address ' Here we will the get the cell address of CTPT ($A$14)
WsEPC.Range(cF.Offset(0, 1), cF.Offset(0, 2).End(xlDown)).Copy
WriteRow = WsCPT.Range("E" & WsCPT.Rows.count).End(xlUp).Row + 1
WsCPT.Range("E" & WriteRow).PasteSpecial (xlPasteValues)
Set cF = .FindNext(cF)
'Look until you find again the first result
Loop While Not cF Is Nothing And cF.Address <> FirstAddress
End If
End With
End With
End Sub
I want a to make some code that searches all the worksheets for the string "Question" then take "5" lines below it. Then take those 5 lines and put them in the worksheet "Template" from lines "B2".
Here is my current code:
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim FirstFound As String
Dim sh As Worksheet
' Set Search value
SearchString = "Question"
Application.FindFormat.Clear
' loop through all sheets
For Each sh In ActiveWorkbook.Worksheets
' Find first instance on sheet
Set cl = sh.Cells.Find(What:=SearchString, _
After:=sh.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not cl Is Nothing Then
' if found, remember location
FirstFound = cl.Address
' format found cell
Do
cl.Font.Bold = True
cl.Interior.ColorIndex = 3
' find next instance
Set cl = sh.Cells.FindNext(After:=cl)
Loop Until FirstFound = cl.Address
End If
Next
All this code does is find the string. How do I take the data below the string and copy them to "Template" worksheet?
You will want to invest in the .Offset Method:
Dim RangeToCopy As Range, DestRow As Long
Set RangeToCopy = sh.Range(cl.Offset(1, 0), cl.Offset(5, 0))
RangeToCopy.Copy
DestRow = Sheets("Template").Range("B" & Rows.Count).End(xlUp).Row + 1
Sheets("Template").Range("B" & DestRow).PasteSpecial xlPasteValues
How can I search for several strings automatically? The number of strings is variable, and are in column A, Sheet “Plan1”, workbook “"Book1.xlsm". I used Find Method for search and a Input Box to find the string, one by one, in a looping for multiple worbooks. I would like to substitute this Input Box to a loop through the strings. Part of my code:
Dim wb As Workbook
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim Escolhe_Cor As String
Dim FirstFound As String
Dim ws As Worksheet
str = InputBox("Digite o número a ser procurado")
Escolhe_Cor = InputBox("Escolha uma cor para destacar esse número. De 3 a 56")
Application.FindFormat.Clear
SearchString = Trim(str)
For Each wb In Workbooks
If wb.Name <> "Book1.xlsm" Then
wb.Activate
If Len(SearchString) = "8" Then
For Each ws In ActiveWorkbook.Worksheets
' Find first instance on sheet
Set cl = ws.Cells.Find(What:=SearchString, _
After:=ws.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not cl Is Nothing Then
' if found, remember location
FirstFound = cl.Address
' format found cell
Do 'etc etc
Try below code :
Dim wb As Workbook
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim Escolhe_Cor As String
Dim FirstFound As String
Dim ws As Worksheet
Dim searchRng As Range, lastRow As Long, cell As Range
Dim lastRow As Long
lastRow = Workbooks("Book1.xlsm").Sheets("Plan1").Range("65000").End(xlUp).Row
Set searchRng = Workbooks("Book1.xlsm").Sheets("Plan1").Range("A2:A" & lastRow) '
For Each cell In searchRng
SearchString = Trim(cell)
For Each wb In Workbooks
If wb.Name <> "Book1.xlsm" Then
wb.Activate
If Len(SearchString) = "8" Then
For Each ws In ActiveWorkbook.Worksheets
' Find first instance on sheet
Set cl = ws.Cells.Find(What:=SearchString, _
After:=ws.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not cl Is Nothing Then
' if found, remember location
FirstFound = cl.Address