ActiveSheet.UsedRange.Columns.Count - 8 what does

2020-02-19 08:26发布

what does ActiveSheet.UsedRange.Columns.Count - 8 mean in vba?

How does vba know the usedRange?

5条回答
Emotional °昔
2楼-- · 2020-02-19 09:04

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
查看更多
祖国的老花朵
3楼-- · 2020-02-19 09:12

UsedRange represents not only nonempty cells, but also formatted cells without any value. And that's why you should be very vigilant.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-02-19 09:13

Seems like you want to move around. Try this:

ActiveSheet.UsedRange.select

results in....

enter image description here

If you want to move that selection 3 rows up then try this

ActiveSheet.UsedRange.offset(-3).select

does this...

enter image description here

查看更多
再贱就再见
5楼-- · 2020-02-19 09:17

I think if you try:

Sub Macro3()
a = ActiveSheet.UsedRange.Columns.Count - 3
End Sub  

with a watch on a you will see it does make a difference.

查看更多
对你真心纯属浪费
6楼-- · 2020-02-19 09:21

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 :

  1. .UsedRange -> "Draws" a box around the outer-most cells with content inside.
  2. .Columns -> Selects the entire columns of those cells
  3. .Count -> Returns an integer corresponding to how many columns there are (in this selection)
  4. - 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.

查看更多
登录 后发表回答