what does ActiveSheet.UsedRange.Columns.Count - 8 mean in vba?
How does vba know the usedRange?
Here's the exact definition of UsedRange
(MSDN reference) :
Every Worksheet object has a UsedRange property that returns a Range object representing the area of a worksheet that is being used. The UsedRange property represents the area described by the farthest upper-left and farthest lower-right nonempty cells in a worksheet and includes all cells in between.
So basically, what that line does is :
.UsedRange
-> "Draws" a box around the outer-most cells with content inside..Columns
-> Selects the entire columns of those cells.Count
-> Returns an integer corresponding to how many columns there are (in this selection)- 8
-> Subtracts 8 from the previous integer.I assume VBA calculates the UsedRange by finding the non-empty cells with lowest and highest index values.
Most likely, you're getting an error because the number of lines in your range is smaller than 3, and therefore the number returned is negative.
BernardSaucier has already given you an answer. My post is not an answer but an explanation as to why you shouldn't be using UsedRange
.
UsedRange
is highly unreliable as shown HERE
To find the last column which has data, use .Find
and then subtract from it.
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastCol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Else
lastCol = 1
End If
End With
If lastCol > 8 Then
'Debug.Print ActiveSheet.UsedRange.Columns.Count - 8
'The above becomes
Debug.Print lastCol - 8
End If
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With