gpt4 book ai didi

vba - 返回从 A1 到最后使用的真正单元格的范围

转载 作者:行者123 更新时间:2023-12-01 18:07:04 32 4
gpt4 key购买 nike

我想选择电子表格中的所有行和列。宏需要是动态的,因为每次调用宏时列数和行数往往会发生变化。它还需要能够考虑空白行和列。

该子例程完成部分过程:

Sub FindLastCell()
Cells.Find(What:="*", After:=[A1], SearchDirection:=xlPrevious).Select
End Sub

它查找并选择电子表格中的最后一个单元格。现在我已经找到电子表格中的最后一个单元格,如何选择单元格 A1 到 LastCell 作为范围?

最佳答案

您需要将这些模组添加到代码中

  1. 工作表可能为空,因此您切勿将SelectFind 一起使用,因为如果Find 不返回任何内容,则会出现错误。相反,测试范围对象 Is Not Nothing
  2. Find可以按行和按列搜索。您需要确定两者最后一行和最后一列,以确定真正的最后使用的单元格
  3. 确定真正的最后一个单元格后,使用Range设置从第一个单元格 (A1) 到通过两个Find范围确定的单元格的范围

请看下面的代码

如果Find获得一个值,那么它会生成一个从A1到两个Find标识的最后使用的单元格的范围rng3

enter image description here

Sub GetRange()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Set rng1 = Cells.Find("*", [a1], xlFormulas, , xlByRows, xlPrevious)
Set rng2 = Cells.Find("*", [a1], xlFormulas, , xlByColumns, xlPrevious)
If Not rng1 Is Nothing Then
Set rng3 = Range([a1], Cells(rng1.Row, rng2.Column))
MsgBox "Range is " & rng3.Address(0, 0)
'if you need to actual select the range (which is rare in VBA)
Application.Goto rng3
Else
MsgBox "sheet is blank", vbCritical
End If
End Sub

关于vba - 返回从 A1 到最后使用的真正单元格的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8283797/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com