0

The below code was working for the intended purpose: copying some rows from one worksheet to another. But, when I added the parts with rangeToDelete, which is meant to clear out the space I'm copying into before each new running of the code. I'm not sure what's happening, but when I use MsgBox to validate some parts of the code, it looks like it's the loop that isn't functioning. But, without kicking up an error, I don't know why.

Option Explicit

Sub findCells()
  Dim topCell As String
  Dim leftCell As String
  Dim refCell As Range
  Dim sht As Worksheet
  Dim lastRow As Long
  Dim i As Long
  Dim cellVal As String
  Dim altCounter As Long
  Dim crange As Range
  Dim rangeToDelete As Range

  Set rangeToDelete = Worksheets("Summary").Cells(31, "A").CurrentRegion
  rangeToDelete.Value = ""

  Set refCell = ActiveCell
  topCell = refCell.End(xlUp).Value
  leftCell = refCell.End(xlToLeft).Value

  Set sht = Worksheets(topCell)
  lastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
  With sht
    .Range("A1:G1").Copy Worksheets("Summary").Range("A31:G31")
    altCounter = 31
    For i = 1 To lastRow
      cellVal = Cells(i, 5).Value
      If leftCell = cellVal Then
        altCounter = altCounter + 1
        Set crange = .Range("A" & i & ":" & "G" & i)
        crange.Copy Worksheets("Summary").Range("A" & altCounter & ":" & "G" & altCounter)
      End If
    Next i
  End With

End Sub
6
  • what is the value of lastrow on entry to the loop? Commented Feb 14, 2017 at 15:42
  • 5
    Don't use .Value ="" but rather .ClearContents. You're filling those cells with an empty string, not clearing them. Commented Feb 14, 2017 at 15:42
  • Or simply like this: rangeToDelete.Clear Commented Feb 14, 2017 at 15:45
  • 1
    Try seeing if adding a dot helps here cellVal = .Cells(i, 5).Value. Commented Feb 14, 2017 at 16:04
  • I made all the suggested changes. It was @SJR 's suggestions that finally fixed it. Commented Feb 14, 2017 at 16:31

1 Answer 1

0

range.cells used numbers not text use 1 for column A in your code. and also use to clear the contents method as suggested.

Sign up to request clarification or add additional context in comments.

1 Comment

.Cells does accept alphabetical column references as well as numerical so .Cells(1, 1) and .Cells(1, "A") are both correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.