首页 > 解决方案 > VBA,在整个工作表中查找最后使用的列

问题描述

我搜索了很多,发现了很多不同的解决方案,但我需要改进我现在使用的解决方案。

我想使用 find 方法查找工作表中最后使用的列,而不考虑已删除的单元格。

我想要的只是获取使用的最后一列,包括起始单元格行中的一列。在下图中,如果我使用我的代码,它将给出最后一列 = 4,因为在第二行数据停止在第 4 列。为什么它不给出 5(标题列)作为结果?

谢谢!!

With ActiveSheet
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
    findlastcol = .Cells.Find(What:="*", _
                  After:=.Range("A1"), _
                  LookAt:=xlPart, _
                  LookIn:=xlFormulas, _
                  SearchOrder:=xlByColumns, _
                  SearchDirection:=xlPrevious, _
                  MatchCase:=False).Column
Else
    findlastcol = 1
End If
End With

示例表 屏幕截图

+---------+---------+---------+---------+---------+
| Header1 | Header2 | Header3 | Header4 | Header5 |
+---------+---------+---------+---------+---------+
| Data    | Data    | Data    | Data    |         |
+---------+---------+---------+---------+---------+

标签: excelvbascripting

解决方案


AutoFilter 启动 Find 方法

  • 除非在您的情况下涉及过滤器,否则该Find方法xlFormulas几乎是“防弹”。
  • 下面的例子展示了如何通过关闭来做到这一点AutoFilter,这并不是人们想要的。它还显示了如何存在三个不需要的参数。此外,它是一种不同的方法,不需要CountA.
  • 一个适当的解决方案是将当前过滤器复制到一个过滤器对象中,然后稍后再应用它。这是一个如何做到这一点的例子。

编码

Sub testBulletProof()
    Dim LastCol As Long
    Dim rng As Range
    With ActiveSheet
        If .AutoFilterMode Then
            .AutoFilterMode = False
        End If
        Set rng = .Cells.Find(What:="*", _
                              LookIn:=xlFormulas, _
                              SearchOrder:=xlByColumns, _
                              SearchDirection:=xlPrevious)
    End With
    If Not rng Is Nothing Then
        LastCol = rng.Column
    Else
        LastCol = 1
    End If
    Debug.Print LastCol
End Sub
  • 由于您可能知道标题所在的行并且数据不会有比标题更多的列,因此您可以使用以下命令:

编码

Sub testFindInRow()
    Dim LastCol As Long
    Dim rng As Range
    With ActiveSheet
        Set rng = .Rows(1).Find(What:="*", _
                                LookIn:=xlFormulas, _
                                SearchDirection:=xlPrevious)
    End With
    If Not rng Is Nothing Then
        LastCol = rng.Column
    Else
        LastCol = 1
    End If
    Debug.Print LastCol
End Sub

推荐阅读