I have a worksheet for every Month from Jan to Dec and a worksheet called Report where the copied data goes
In the Months sheet I have the following Data
ID NAME # DAYS OF VACATION
1 GEORGE 3
2 MARY 5
Every Month sheet has the same names but the names are not bound to the same ID
What i want to do in Summary sheet is
ID NAME # DAYS OF VACATION MONTH
1 GEORGE 3 JAN
2 GEORGE 2 FEB
SUM GEORGE 5 YEAR
What I have managed to do is to copy from one Month sheet to Report but I can't copy multiple from all the Month sheets and I don't know how to do the SUM part. Any ideas?
Sub SearchForString()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
'Start search in row 2
LSearchRow = 2
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = 2
fname = InputBox("Enter Name", "Enter Data")
If fname = "" Then
While fname = ""
MsgBox ("Enter Name")
fname = InputBox("Enter Name", "Enter Data")
Wend
End If
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
'If value in column E = "Mail Box", copy entire row to Sheet2
If Sheets("JAN").Range("B" & CStr(LSearchRow)).Value = fname Then
'Select row in Sheet1 to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into Sheet2 in next row
Sheets("REPORT").Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
'AddWatermark ("JAN")
'Move counter to next row
LCopyToRow = LCopyToRow + 1
End If
'Go back to Sheet1 to continue searching
Sheets("REPORT").Select
LSearchRow = LSearchRow + 1
Wend
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
MsgBox "COPY DONE"
Exit Sub
Err_Execute:
MsgBox "ERROR"
End Sub
What you'll need to do is loop through each of your month sheets, and while on each sheet, loop through all the data to find values on that sheet that match your name indicated name (fName in your code). Two loops total. Also, check out this link as a starter, but you should also avoid selecting and copying when writing VBA code.
The basic code you'd be looking for (with some assumptions made) would be the following
'Assuming Jan is the first sheet and Dec is the 12th sheet in the workbook
lCopyToRow = 2
for i = 1 to 12
lSearchRow = 2
do while Len(Sheets(i).Cells(lSearchRow,1).value) > 0
If Sheets(i).Cells(lSearchRow,2).value = fName then
Sheets("Summary").range(Sheets("Summary").Cells(lCopyToRow,1), _
Sheets("Summary").Cells(lCopyToRow,3)) = _
Range(Sheets(i).Cells(lSearchRow,1), _
Sheets(i).Cells(lSearchRow,3)).value
lCopyToRow = lCopyToRow + 1
End If
lSearchRow = lSearchRow + 1
Loop
Next i
It took my a while buty I ended up with a new code that works faster and does exactly the job I needed.
I have the following Worksheets DATA,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,SUMMARY
The following code search for a certain text, and copies the row from every worksheet except DATA and SUMMARY, to SUMMARY worksheet. In the end I sum up some integers to get the result I want. Thanks to everyone spend some time in my question.
Sheets("SUMMARY").Cells.Clear
Dim rFind As Range, fname As String, sAddr As String, ws As Worksheet
fname = InputBox("Input Name", "Input Name")
If fname = "" Then
While fname = ""
MsgBox ("Fatal Error")
fname = InputBox("Input Name", "Input Name")
Wend
End If
For Each ws In Worksheets
If (ws.Name <> "SUMMARY") And (ws.Name <> "DATA") Then
With ws.UsedRange.Range("B2", "AK36")
Set rFind = .Find(What:=fname, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
sAddr = rFind.Address
Do
rFind.EntireRow.Copy Sheets("SUMMARY").Range("A" & Rows.Count).End(xlUp)(2)
Set rFind = .FindNext(rFind)
Loop While rFind.Address <> sAddr
sAddr = ""
End If
End With
End If
Next ws
Dim LR As Long
With Sheets("SUMMARY")
LR = .Range("G" & Rows.Count).End(xlUp).Row
.Range("G" & LR + 1).Value = WorksheetFunction.Sum(.Range("G1:G" & LR))
Related
I hope you can help.
I have a lengthy piece of code, CODE 2 what this does is it allows a user to open a dialog box, select a sheet, once a sheet is selected it formats the sheet, filters the 7th column then adds new sheets with copied information from 7th column, names the sheets, formats again, adds and deletes columns, subtracts dates and returns numbers, and I essentially end up with what you see in Pic 1 (more happens but that is the gist of it) I am happy with CODE 2
I also have CODE 1 now with this if a user selects a value in A2 that is not "Enter Your Country Here" then all the "Enter Your Country Here" in the workbook get replaced with the new value in A2.
CODE 1 also works fine
The problem is i cant seem to join CODE 1 into CODE 2. CODE 1 works perfectly by itself but I cant seem to call it or get it to fire where ever I place or call it in CODE 2
Can CODE 1 be worked into CODE 2 so that when a user selects a country it finds and replaces "Enter Your Country Here" with the selected value in A2
Like a said both codes work fine separately I just need to bring 1 into 2 some how
As always any and all help is greatly appreciated.
Pic 1
CODE 1
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("A2")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
Call Find_Replace
End If
End Sub
Public Sub Find_Replace()
Dim sht As Worksheet
Dim fnd As Variant
Dim rplc As Variant
fnd = "Enter Your Country Here"
rplc = Worksheets("SearchCasesResults").Range("A2").Value
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace what:=fnd, Replacement:=rplc, _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
End Sub
CODE 2
Sub Open_Workbook_Dialog()
Dim my_FileName As Variant
MsgBox "Pick your Disputes file" '<--| txt box for prompt to pick a file
my_FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*") '<--| Opens the file window to allow selection
If my_FileName <> False Then
Workbooks.Open Filename:=my_FileName
Call Sort_Disputes '<--|Calls Sort Disputes and begins to format
End If
End Sub
Public Sub Sort_Disputes()
With ActiveWorkbook.Sheets(1)
Rows("1:5").Delete '<--|Deletes the first 5 rows
Range("A1").EntireColumn.Insert '<--|Inserts a new A column
Range("A1").Value = "Market" '<--|Market text enters cell A1
Cells(1, 2).Copy
Cells(1, 1).PasteSpecial (xlPasteFormats) '<--|Keeps the formatting of other columns and forces to new column A
Application.CutCopyMode = False
Columns.AutoFit '<--|Auto fits the columns
Range("C:C,J:J,M:AF").EntireColumn.Delete '<--|Deletes Columns
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Call populateA '<--|Calls PopulateA and this takes a look a Column A and where blank enters text
End With
Call Filter '<--|Calls Filter which looks down the 7th Column and seperates out the sheets to new tabs based on the value in Column 7
Call Activate_Sheet '<--|Deletes a column then subtracts todays date from the date in C and represents as a number in D
Call Activate_Sheet_2 '<--|As long as C is not blank it will subtract the Date in C from the Date in D and return a numerical result
Call Add_Sheet
End Sub
Public Sub Filter()
Dim rCountry As Range, helpCol As Range
With ActiveWorkbook.Sheets(1) '<--| refer to data worksheet
With .UsedRange
Set helpCol = .Resize(1, 1).Offset(, .Columns.Count) '<--| get a "helper" column just at the right of used range, it'll be used to store unique country names in
End With
With .Range("A1:Q" & .Cells(.Rows.Count, 1).End(xlUp).Row) '<--| refer to its columns "A:Q" from row 1 to last non empty row of column "A"
.Columns(7).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=helpCol, Unique:=True '<-- call AdvancedFilter on 7th column of the referenced range and store its unique values in "helper" column
Set helpCol = Range(helpCol.Offset(1), helpCol.End(xlDown)) '<--| set range with unique names in (skip header row)
For Each rCountry In helpCol '<--| iterate over unique country names range (skip header row)
.AutoFilter 7, rCountry.Value2 '<--| filter data on country field (7th column) with current unique country name
If Application.WorksheetFunction.Subtotal(103, .Cells.Resize(, 1)) > 1 Then '<--| if any cell other than header ones has been filtered...
Worksheets.Add Worksheets(Worksheets.Count) '<--... add new sheet
ActiveSheet.Name = rCountry.Value2 '<--... rename it
.SpecialCells(xlCellTypeVisible).Copy ActiveSheet.Range("A1") 'copy data for country under header
End If
Next
End With
.AutoFilterMode = False '<--| remove autofilter and show all rows back
End With
helpCol.Offset(-1).End(xlDown).EntireColumn.Delete '<--| clear helper column (header included)
End Sub
Public Sub populateA()
Dim WS As Worksheet
Dim lRow As Long
Set WS = ActiveWorkbook.Sheets(1)
With WS
lRow = .Range("B" & .Rows.Count).End(xlUp).Row '<--| Looks for the last empty cell in Column B
.Range("A2:A" & lRow).Formula = "=If(B2<>"""",""Enter Your Country Here"","""")" '<--| If there is no blank cell in B and A has a blank cell then A gets populated with "Enter your Country Here"
.Range("A2:A" & lRow).Value = .Range("A2:A" & lRow).Value
.Range("A2:A" & lRow).Interior.ColorIndex = 39 '<--|Changes the colour of A
End With
End Sub
Public Sub Activate_Sheet()
Worksheets("In Progress").Activate '<--|Activates Inprogress Sheet
Columns.AutoFit '<--|Auto fits Columns
Range("N:N").EntireColumn.Delete '<--|Delete Columns
Range("D1").Value = "# days open" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Dim LastRow As Long, i As Long
With Worksheets("In Progress")
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row '<--|Looks for the last non empty cell in C
For i = 2 To LastRow
.Range("D" & i).Value = DateDiff("d", .Range("C" & i).Value, Date) '<--|As long as C is not blank it will subtract todays date from C and populate in D
Next i
End With
End Sub
Public Sub Activate_Sheet_2()
Worksheets("Complete").Activate '<--|Activates Complete Sheet
Columns.AutoFit '<--|Auto fits Columns
Range("N:N").EntireColumn.Delete '<--|Deletes Columns
Range("E1").EntireColumn.Insert '<--|Inserts Columns
Range("E1").Value = "Overall Ticket Aging" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Dim LastRow As Long, i As Long
With Worksheets("Complete")
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
For i = 2 To LastRow
.Range("E" & i).Value = DateDiff("d", .Range("C" & i).Value, .Range("D" & i).Value) '<--|As long as C is not blank it will subtract the Date in C from the Date in D and return a numerical result
Next i
End With
Columns(5).NumberFormat = "0" '<--|Formats the 5 column to number format
End Sub
Public Sub Add_Sheet()
''Dim WS As Worksheet
''Set WS = Sheets.Add
Sheets.Add.Name = "Countries"
Worksheets("Countries").Activate
Range("A1").Value = "Country"
Range("A2").Value = "UK"
Range("A3").Value = "Belgium"
Range("A4").Value = "Bulgaria"
Range("A5").Value = "Croatia"
Range("A6").Value = "Czech Republic"
Range("A7").Value = "Slovenia"
Range("A8").Value = "Spain"
Range("A9").Value = "Italy"
Range("A10").Value = "Germany"
Worksheets("SearchCasesResults").Activate
Call Auto_Filter
End Sub
Public Sub Auto_Filter()
'replace "J2" with the cell you want to insert the drop down list
With Range("A2").Validation
.Delete
'replace "=A2:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Countries!A2:A10"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
To solve this I needed VBA code that would put Change Event VBA code into another worksheet. Calling the code I had was not working as I was calling a Change Event which didn't make sense. I needed code to put the change event into the sheet.
The code I used to put the change event into the the sheet in my example in the pic the sheet named "SearchCasesResults" is below I hope it helps someone.
CODE to put code into another sheet
Public Sub CreateEventProcedure()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim LineNum As Long
Const DQUOTE = """" ' one " character
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("Sheet1")
Set CodeMod = VBComp.CodeModule
With CodeMod
LineNum = .CreateEventProc("Change", "Worksheet")
LineNum = LineNum + 1
''.InsertLines LineNum, " MsgBox " & DQUOTE & "Hello World" & DQUOTE
''.InsertLines LineNum, " Cells.Columns.AutoFit"
''.InsertLines LineNum, " End Sub"
.InsertLines LineNum, " Worksheets(" & DQUOTE & "SearchCasesResults" & DQUOTE & ").Activate"
.InsertLines LineNum, " Next sht"
.InsertLines LineNum, " SearchFormat:=False, ReplaceFormat:=False"
.InsertLines LineNum, " LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _"
.InsertLines LineNum, " sht.Cells.Replace what:=fnd, Replacement:=rplc, _"
.InsertLines LineNum, " For Each sht In ActiveWorkbook.Worksheets"
.InsertLines LineNum, " rplc = Worksheets(" & DQUOTE & "SearchCasesResults" & DQUOTE & ").Range(" & DQUOTE & "A2" & DQUOTE & ").Value"
.InsertLines LineNum, " fnd = " & DQUOTE & "Enter Your Country Here" & DQUOTE & ""
.InsertLines LineNum, " Dim rplc As Variant"
.InsertLines LineNum, " Dim fnd As Variant"
.InsertLines LineNum, " Dim sht As Worksheet"
End With
End Sub
Example
I have spreadsheet(Sheet2) like
I need to search "Tran1" and "app" full row data from my excel-sheet and after searching the record I need to copy the rows into Sheet3.
Currently I am able to do it only for 1 record "Tran1" but i need to do it with multiple values.
Here is my code snippet:
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
LSearchRow = 4
LCopyToRow = 2
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
If InStr(1, Range("A" & CStr(LSearchRow)).Value, "tran1") > 0 Then
'Select row in Sheet2 to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into Sheet3 in next row
Sheet3.Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet2 to continue searching
Sheet2.Select
End If
LSearchRow = LSearchRow + 1
Wend
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An error occurred."
Can anyone let me tell how to do with multiple search.?
Here is a possible solution for your request:
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
dim lCounter as long
On Error GoTo Err_Execute
LSearchRow = 4
LCopyToRow = 2
dim varValues(3) as variant
varValues(0) = "tran1"
varValues(1) = "tran2"
varValues(2) = "tran3"
for lCounter = lbound(varValues) to ubound(varValues)
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
If InStr(1, Range("A" & CStr(LSearchRow)).Value, varValues(0)) > 0 Then
'Select row in Sheet2 to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into Sheet3 in next row
Sheet3.Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet2 to continue searching
Sheet2.Select
End If
LSearchRow = LSearchRow + 1
Wend
next
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An error occurred."
lCounter and varValues are further declared. varValues gets 2 more values, tran1, tran2 and tran3. Thus, I have created a for loop, that loops all over them. The logic in the While loop is left.
In general, your code uses Select, which is a bad practise in VBA, but as far as it works it is ok. Here is how to avoid the selection - How to avoid using Select in Excel VBA macros
A simple use of And in you If statement will do the trick!
(I've tested the column B for "app", I'll let you tune it to the right column ;) )
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
LSearchRow = 4
LCopyToRow = 2
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
If InStr(1, Sheet2.Range("A" & CStr(LSearchRow)).Value, "tran1") > 0 And _
InStr(1, Sheet2.Range("B" & CStr(LSearchRow)).Value, "app") > 0 Then
'Select row in Sheet2 to copy
Sheet2.Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Copy
'Paste row into Sheet3 in next row
Sheet3.Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
End If
LSearchRow = LSearchRow + 1
Wend
'Position on cell A3
Application.CutCopyMode = False
Sheet2.Range("A3").Select
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An error occurred."
AutoFilter() gets things quite easy and short:
Sub Main()
With Sheets("Sheet2") '<--| reference "data" sheet
With .Range("C1", .Cells(.Rows.count, "A").End(xlUp)) '<--| reference its columns A:C range from row 1 (headers) down to column A last not empty row
.AutoFilter field:=1, Criteria1:=Array("tran1", "app"), Operator:=xlFilterValues '<--| filter referenced range on its 1st column (i.e. "Name") with "tran" and "app"
If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then .Resize(.Rows.count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Copy Sheets("Sheet3").Cells(2, 1) '<--| if any filterd cells other than header then copy them and paste to Sheets("Sheet3") from its row 2
End With
.AutoFilterMode = False
End With
End Sub
I have two UserForms in my Worksheet, one to add clients and one to remove. The "Add Client" works perfect, however the "Remove Client" does not. I have used Breakpoints to see where my code is going wrong and what seems to be happening is it skips from "Private Sub OkButton2_Click()" to "On Error GoTo Err_Execute" and from "If Range("A" & CStr(LSearchRow)).Value = DCNameTextBox1.Value Then" all the way down to "End If"
I want the VBA upon the user clicking Okay to search for what was input in the Name box, cut that row from A to F(deleting the entire row), paste the info in the next empty row in sheet 2 and add the additional info the user put into the user form. I have looked at a lot of different codes and questions and none of them seem to quite do what I want.
Private Sub OkButton2_Click()
Dim emptyRow As Long
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
'Start search in row 3
LSearchRow = 3
'Start copying data to row 3 in Sheet2 (row counter variable)
LCopyToRow = 3
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
'If value in column A = "Client Name", copy entire row to Sheet2
If Range("A" & CStr(LSearchRow)).Value = DCNameTextBox1.Value Then
'Select row in Sheet1 to copy
Rows(CStr(LSearchRow) & "A:F" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into Sheet2 in next row
Sheets("Sheet2").Select
Rows(CStr(LCopyToRow) & "A:F" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
'Add/Transfer Discharge info
Sheets("Sheet2").Cells(emptyRow, 7).Value = DCDateTextBox.Value
Sheets("Sheet2").Cells(emptyRow, 8).Value = DispoTextBox.Value
Sheets("Sheet2").Cells(emptyRow, 9).Value = ReasonTextBox.Value
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet1 to continue searching
Sheets("Sheet1").Select
End If
LSearchRow = LSearchRow + 1
Wend
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
MsgBox "Client has been moved to Discharge list."
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
Using Range.Find is a little more efficient.
Private Sub OkButton2_Click()
Dim Source As Range, Target As Range
With Worksheets("Sheet1")
Set Source = .Range("A3", .Range("A" & .Rows.Count).End(xlUp))
End With
Set Target = Source.Find(What:=DCNameTextBox1.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not Target Is Nothing Then
'Reference the next enmpty row on Sheet2
With Worksheets("Sheet2")
With .Range("A" & .Rows.Count).End(xlUp).Offset(1)
'.Range("A1:F1") is relative to the row of it's parent range
.Range("A1:F1").Value = Target.Range("A1:F1").Value
.Range("H1:J1").Value = Array(DCDateTextBox.Value, DispoTextBox.Value, ReasonTextBox.Value)
Set Source = .Range("A3", .Range("A" & .Rows.Count).End(xlUp))
End With
End With
Target.Range("A1:F1").Delete Shift:=xlShiftUp
MsgBox "Client has been moved to Discharge list."
Else
MsgBox "Client not found", vbInformation, "No Data"
End If
Range("A3").Select
End Sub
I need to copy the row contents from 3 specific columns from different worksheets on my workbook, to a particular range in a particular worksheet. e.g in Sheet1 I have a range from B1 to E40 I want to copy the contents from Columns B to D that display “TRUE” in column E and then paste it to Worksheet named “Analysis”.
I want the macro to go in Sheet 2, Sheet 3 and Sheet 4 and do the same (look for TRUE in column E and copy the rows B to D that meet that criteria) and paste the values one below the other in worksheet “Analysis”.
I’m pretty new to VBA and I have found a code that I think will be helpful to start with but I need help. Could you please give me an idea? I enclose the code that I found so that you can give me your comments it might not be the one needed but at list it might be a base. Many thanks.
Sub MyCode()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
'Start search in row 3
LSearchRow = 3
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = 2
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
'If value in column BA = "Soccer", copy entire row to Sheet2
If Range("BA" & CStr(LSearchRow)).Value = "Soccer" Then
'Select row in Sheet1 to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into Sheet2 in next row
Sheets("Sheet2").Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
'Move counter to next row
LCopyToRow = LCopyToRow + 1
'Go back to Sheet1 to continue searching
Sheets("Sheet1").Select
End If
LSearchRow = LSearchRow + 1
Wend
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
This should work for Sheet1. However you need to clarify where exactly you want to copy the values to on the "Analysis"-sheet.
Dim i As Long, j As Long, lR As Long, lastRow As Long, k As Long
Dim ws As Worksheet
lastRow = 1
For k = 1 To ThisWorkbook.Worksheets.Count
If Sheets(k).Name <> "Analysis" Then
Set ws = Sheets(k)
lR = ws.Cells(ws.Rows.Count, 5).End(xlUp).Row
For i = 1 To lR
If ws.Cells(i, 5).Value = True Then
lastRow = lastRow + 1
For j = 2 To 4 '2 represents Columns(2) = B and 4 represents Columns(4) = D
If ws.Cells(i, j).Value <> "" Then
ThisWorkbook.Worksheets("Analysis").Cells(lastRow, j - 1).Value = ws.Cells(i, j)
End If
Next j
End If
Next i
End If
Next k
Scenario: Each row would contain 23 columns; 20 would contain user populated data and the last 3 would be autogenerated through vba.
While running if the vba code identifies the first 20 columns of any row to be blank cells then the whole row is declared blank and highlighted.
I have been able to write the following code:
For Each rng In Range("A1:A" & LastRow)
With rng
If .Value < 1 Then
MsgBox "Blank Cell found"
blnkcnt = 0
For Each mycl In Range("A" & ActiveCell.Row & ":T" & ActiveCell.Row)
With mycl
If .Value < 1 Then
blnkcnt = blnkcnt + 1
End If
End With
Next mycl
If blnkcnt = 20 Then
lCount = lCount + 1
With .EntireRow.Interior
.ColorIndex = 6
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
End If
End If
End With
Next rng
If lCount > 0 Then
MsgBox "Data contains blank row(s): " & lCount
End
Else
MsgBox "No blank Rows"
End If
I've used a COUNTBLANK function on the first 20 columns of each row to determine if any blank cells exist.
Dim rng As Range, lCount As Long, LastRow As Long
With ActiveSheet 'set this worksheet properly!
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each rng In .Range("A1:A" & LastRow)
With rng.Resize(1, 20)
If Application.CountBlank(.Cells) = 20 Then 'All 20 cells are blank
lCount = lCount + 1
.EntireRow.ClearContents
.EntireRow.Interior.ColorIndex = 6
End If
End With
Next rng
End With
If lCount > 0 Then
MsgBox "Data contains blank row(s): " & lCount
Else
MsgBox "No blank Rows"
End If
If all 20 cells are blank then the entire row is made blank and yellow highlighting is applied.
I'm using the COUNTBLANK function as it was not clear on whether you have zero-length strings returned by formulas. COUNTBLANK will count these as blanks.
Don't use that. Use CountA to check if there is any data in those 20 columns.
See this (untested)
Dim ws As Worksheet
Dim i As Long
'~~> Change this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find lastrow and change accordingly
'~~> For demonstration purpose using a hard coded value
lastrow = 10
For i = 1 To lastrow
'~~> Use CountA to check if there is any data
If Application.WorksheetFunction.CountA(.Range("A" & i & ":T" & i)) = 0 Then
MsgBox "Row " & i & " is blank"
'
'~~> Rest os your code
'
End If
Next i
End With