Set wscf = Sheets(Range("I2").Value) Set wsjr = Sheets("Reminders") lastRow =…
- User
Set wscf = Sheets(Range("I2").Value) Set wsjr = Sheets("Reminders")
lastRow = wscf.Cells(Rows.count, "B").End(xlUp).Row
For i = 5 To lastRow If wscf.Cells(i, "I").Value = "" Then MsgBox ("Found") Set copyRange = wscf.Range("J" & i) If Not IsEmpty(copyRange) Then wsjr.Range("D8").Resize(copyRange.Rows.count, 1).Value = copyRange.Value MsgBox ("Print") End If End If Next i
Currently in the code above all instances of copyRange are overwriting themselves on D8. I want this code to start the copyRange at D8 but for next instance of copyRange to move to D9 and the next to D10 and so forth
- Assistant
To modify the code so that each instance of
copyRangestarts copying to the next row in column D, you can introduce a variable that keeps track of the current row and increment it inside the loop. Here's an updated version of the code that accomplishes this:Set wscf = Sheets(Range("I2").Value) Set wsjr = Sheets("Reminders") lastRow = wscf.Cells(Rows.Count, "B").End(xlUp).Row currentRow = 8 ' Start at row 8 in column D For i = 5 To lastRow If wscf.Cells(i, "I").Value = "" Then MsgBox ("Found") Set copyRange = wscf.Range("J" & i) If Not IsEmpty(copyRange) Then wsjr.Range("D" & currentRow).Resize(copyRange.Rows.Count, 1).Value = copyRange.Value currentRow = currentRow + copyRange.Rows.Count ' Increment currentRow by the number of rows in copyRange MsgBox ("Print") End If End If Next iIn this updated code, the variable
currentRowis initialized to 8 before the loop starts. Inside the loop,currentRowis used to determine the starting row in column D (Range("D" & currentRow)). After copying the to the destination, is incremented by the number of rows in (). This ensures that each subsequent starts copying to the next row in column D. - User
variable currentRow is not defined
- Assistant
Apologies for the oversight. To fix the error, you need to declare the variable
currentRowbefore using it in the code. Add the lineDim currentRow As Longat the beginning of your code, beforeSet wscf = Sheets(Range("I2").Value). Here's the updated code:Dim currentRow As Long ' Declare currentRow variable Set wscf = Sheets(Range("I2").Value) Set wsjr = Sheets("Reminders") lastRow = wscf.Cells(Rows.Count, "B").End(xlUp).Row currentRow = 8 ' Start at row 8 in column D For i = 5 To lastRow If wscf.Cells(i, "I").Value = "" Then MsgBox ("Found") Set copyRange = wscf.Range("J" & i) If Not IsEmpty(copyRange) Then wsjr.Range("D" & currentRow).Resize(copyRange.Rows.Count, 1).Value = copyRange.Value currentRow = currentRow + copyRange.Rows.Count ' Increment currentRow by the number of rows in copyRange MsgBox ("Print") End If End If Next iBy adding the line
Dim currentRow As Long, we are declaringcurrentRowas a variable of typeLongbefore using it in the loop.