I'm trying to implement a simple for-each statement that is supposed to copy data from one worksheet (template) to another (raw data), followed by a another 'clean-up' for-each + If statement, which is supposed to clear all the cells previously copied except for 5 cells which have pre-defined calculations.
I began with for-each statement which cleared all the fields (and worked OK), except for the fact that later I figured that I need exceptions on some of the fields. So, I added a simple If statement which instructs the sub to go to the next cell without clearing it in case of those few particular cell ranges.
For some reason when running that code, it clears all the fields from within the defined range except for field K15 which isn't included in the exception, and I have no idea why that happens ;__; I tried troubleshooting that but can't come up with anything.
My code is pasted below. Any advice will be appreciated - including any tips to improve the code. Thanks!
Sub CopyData()
Dim TargetRow, CopyRange, Cell As Range
Dim RowCount, ColumnCount, ColumnLast, ColC As Long
Dim ws As Worksheet
Application.ScreenUpdating = False
ColumnCount = 1
ColumnLast = 51
ColC = 1
Set ws = ThisWorkbook.ActiveSheet
Set CopyRange = Range("C10:C15,C17:C18,E12,E17:E18,K4:K6,K9,K11:K45")
Sheets("RawData").Activate
RowCount = Range("A1").CurrentRegion.Rows.Count + 1
Set TargetRow = Range(Cells(RowCount, ColumnCount), Cells(RowCount, ColumnLast))
For Each Cell In CopyRange
TargetRow.Cells(ColC).Value = Cell.Value
ColC = ColC + 1
Next Cell
ws.Activate
For Each Cell In CopyRange
If Cell = Range("K4") Or Cell = Range("K5") Or Cell = Range("K6") Or Cell = Range("K9") _
Or Cell = Range("K46") Then
GoTo Forward
Else
Cell.Value = ""
End If
Forward:
Next Cell
Application.ScreenUpdating = True
End Sub
Cell = Range("K4")(etc) is shorthand forCell.Value = Range("K4").Value? ThatIfstatement is comparing the value of each cell to the values of various other cells, it is not comparing the addresses. (I couldn't understand the question - too early in the morning and I haven't had my morning coffee yet - but, if that is the issue, useCell.Address = "$K$4"etc.) Or maybe have two ranges - one for copying and one for cleaning up (which excludes the ones you don't want to clean up).