The VBA code below searches all sheets in my workbook with a three letter name, for the…
- User
The VBA code below searches all sheets in my workbook with a three letter name, for the value in cell A1. The results of the search are copied to column B:K starting from Row 2. Row 1 is my Header Row. I would like to sort the data collected after this VBA event has been run by date in column I. However, if the search value in A1 is 'Service', then the sort will be based on the date in column H. Can you please adjust the code below to do this.
Sub FindAndCopyRows() Dim selectedValue As String Dim ws As Worksheet Dim cTasksWs As Worksheet Dim lastRow As Long, pasteRow As Long ' Get the selected value from cell A1 selectedValue = Range("A1").Value ' Set the "CTasks" worksheet as the destination for copied rows Set cTasksWs = ThisWorkbook.Worksheets("CTasks") ' Clear the previous data in CTasks worksheet cTasksWs.Range("B2:J" & cTasksWs.Cells(Rows.Count, "B").End(xlUp).Row).Clear cTasksWs.Range("K2:K" & cTasksWs.Cells(Rows.Count, "K").End(xlUp).Row).Clear Application.ScreenUpdating = False Application.DisplayAlerts = False ' Loop through all sheets in the workbook For Each ws In ThisWorkbook.Worksheets ' Check if the sheet name has only three letters If Len(ws.Name) = 3 Then ' Find the matching value in column B lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row For i = 2 To lastRow If ws.Cells(i, "B").Value = selectedValue Then ' Copy the row B:J to CTasks sheet pasteRow = cTasksWs.Cells(cTasksWs.Rows.Count, "B").End(xlUp).Row + 1 ws.Range("B" & i & ":J" & i).Copy Destination:=cTasksWs.Range("B" & pasteRow & ":J" & pasteRow) ' Write the sheet name to column K in CTasks sheet cTasksWs.Cells(pasteRow, "K").Value = ws.Name End If Next i End If Next ws cTasksWs.Range("L2:L101").Calculate cTasksWs.Range("N1:X1").Copy Range("B1:L1") cTasksWs.Range("A23").Value = "" cTasksWs.Range("A20").Value = "CURRENT TASKS" cTasksWs.Range("B1:L1").Interior.Color = RGB(0, 0, 0) ' Black Application.ScreenUpdating = True Application.DisplayAlerts = True cTasksWs.Range("A20").Select End Sub
- Assistant
- User
Does your suggestion account for the fact that Row 1 is my header row and should not be part of the sorted data
- Assistant
- User
In my initial request I stated that if the search value in A1 is ‘Service’, then the sort will be based on the date in column H. It appears that your code might not be doing this
- Assistant