I have a sheet where data is written to, before this can happen it first needs to be emptied.
The sheet has a header which is 3 rows thick and is on the worksheet from A1:NQY3
but may stretch as far as A1:NVU3
The method I chose to empty the sheet is:
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
.Range(.cells(4, 1), .Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count)).Delete
End With
The procedure above works fine and all data, formatting and data validation rules is gone. The problem occurs when I run the procedure again on an empty sheet. The procedure would then delete the third header rows as the .UsedRange.Rows.Count
should evaluate to 3 and the range to delete would become .Range(.Cells(4, 1), .Cells(3, 9931))
(NQY is column 9931)
To avoid this I added a check:
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
If .UsedRange.Rows.Count = 3 Then Exit Sub
.Range(.cells(4, 1), .Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count)).Delete
End With
When stepping through this on a sheet which had just been emptied by the first procedure, I checked what the .UsedRange
evaluated to since the procedure stepped to the .Delete
part of the procedure instead of the Exit Sub
as I expected. The .UsedRange
evaluated to A1:NQY6
instead of the expected A1:NQY3
To find if there was any data in this range that was not in the header range I ran:
For Each cl In .UsedRange
If Not cl = Empty And cl.Row > 3 Then
MsgBox "Data found in " & cl.Address & "."
End If
Next
When I ran this, the message box did not pop up indicating to me there is no data in that range. Why is it that when I delete a range, based on the UsedRange dimensions, the used range is larger than expected?