excel - 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 | |
+---------+---------+---------+---------+---------+
解决方案
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
推荐阅读
- java - 如何使用 Chrome 配置文件无头运行 Webdriver
- amazon-web-services - 如果未找到文件,则禁用 Cloudfront 缓存
- typescript - 如何从离子中的承诺中返回价值
- r - 你如何将你的cutree结果链接回你的数据框
- javascript - 如何在圆内绘制三角形指针
- java - 标签的 JavaFX 鼠标单击事件
- python - Python3:在 GUVI 上输入时出现 EOF 错误
- cmake - 如何每次 cmake 调用只打印一次消息?
- deployment - Nextjs/postcss css 变量在生产中不可用 (Zeit)
- r - 错误的维度数量股票价格