Reputation: 13
I'm trying to do the following with an excel macro. When a date is entered into a cell on sheet 1 I want to take specific cells from that row and copy them to a new row on sheet 2. Here is an example.
This would be sheet 1.
A B C D E
proj1 mary started - fiber
proj2 jack complete 2/7/2014 fiber
proj3 kim started - cat6
proj2 phil complete 2/9/2014 fiber
Sheet 2 should then look like this since two of them have dates and I only want to bring over specifically the cells from row A,C and D.
A B C
proj2 complete 2/7/2014
proj2 complete 2/9/2014
With the following code I found I'm able to bring over an entire row based on a word value in a cell but not just the specific ones I want and of course I want it to trigger based on a date being entered not the words "reply" or "response". Any help would be appreciated.
Sub Foo()
Dim i As Long, iMatches As Long
Dim aTokens() As String: aTokens = Split("reply,response", ",")
For Each cell In Sheets("sheet1").Range("D:D")
If (Len(cell.Value) = 0) Then Exit For
For i = 0 To UBound(aTokens)
If InStr(1, cell.Value, aTokens(i), vbTextCompare) Then
iMatches = (iMatches + 1)
Sheets("sheet1").Rows(cell.Row).Copy Sheets("sheet2").Rows(iMatches)
End If
Next
Next
End Sub
Upvotes: 1
Views: 31179
Reputation: 12497
This may help. It needs to be placed in the Worksheet_Change
section.
This assumes your data is in Columns A:E
in Sheet1
and you want to copy data over to Sheet2
once you have entered a date.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim nextRow As Long
If Not Intersect(Target, Range("D:D")) Is Nothing Then
If VBA.IsDate(Target) Then
With Worksheets("Sheet2")
nextRow = IIf(VBA.IsEmpty(.Range("A1048576").End(xlUp)), 1, .Range("A1048576").End(xlUp).Row + 1)
.Range("A" & nextRow) = Target.Offset(0, -3)
.Range("B" & nextRow) = Target.Offset(0, -1)
.Range("C" & nextRow) = Target
End With
End If
End If
End Sub
Upvotes: 2