学习Excel技术,关注微信公众号:
excelperfect
标签:
AI-Excel
,
deepseek
,
VBA
查找并获取工作表数据区域最后一行,是
Excel VBA
编程时经常要使用的代码。工作表数据区域不同,代码会有所不同,但有些是通用的代码,适合各种情形;有些可能只适合特定的情形。下面,我们看看
deepseek
是怎么给我们答案的。
向
deepseek
提问:
请帮我使用
VBA
获取工作表中数据区域的最后一行,要求:
1.
考虑不同情况;
2.
多使用几种方法。
下面是
deepseek
给出的代码:
' 方法1:通过列查找(推荐单列数据场景)
Function GetLastRow_Method1(ws As Worksheet) As Long
' 从A列底部向上查找(可修改列字母)
GetLastRow_Method1 = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
End Function
' 方法2:UsedRange属性(适合规范数据区域)
Function GetLastRow_Method2(ws As Worksheet) As Long
If ws.UsedRange.Rows.Count = 0 Then
GetLastRow_Method2 = 0
Else
GetLastRow_Method2 = ws.UsedRange.Rows.Count + ws.UsedRange.Row - 1
End If
End Function
' 方法3:多列校验取最大值(适合多列数据不一致时)
Function GetLastRow_Method3(ws As Worksheet) As Long
Dim lastRow As Long, tempRow As Long
lastRow = 0
With ws
' 检查A列、C列、F列(可根据需要修改列索引)
tempRow = .Cells(.Rows.Count, 1).End(xlUp).Row
If tempRow > lastRow Then lastRow = tempRow
tempRow = .Cells(.Rows.Count, 3).End(xlUp).Row
If tempRow > lastRow Then lastRow = tempRow
tempRow = .Cells(.Rows.Count, 6).End(xlUp).Row
If tempRow > lastRow Then lastRow = tempRow
End With
GetLastRow_Method3 = lastRow
End Function
' 方法4:Find方法(最全面方法)
Function GetLastRow_Method4(ws As Worksheet) As Long
GetLastRow_Method4 = ws.Cells.Find( _
What:="*", _
After:=ws.Range("A1"), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False _
).Row
End Function
' 方法5:SpecialCells方法(快速但需注意格式残留)
Function GetLastRow_Method5(ws As Worksheet) As Long
On Error Resume Next ' 处理空工作表情况
GetLastRow_Method5 = ws.Cells.SpecialCells(xlCellTypeLastCell).Row
If Err.Number <> 0 Then GetLastRow_Method5 = 0
On Error GoTo 0
End Function
' 使用示例:
Sub TestMethods()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Debug.Print "方法1结果:" & GetLastRow_Method1(ws)
Debug.Print "方法2结果:" & GetLastRow_Method2(ws)
Debug.Print "方法3结果:" & GetLastRow_Method3(ws)
Debug.Print "方法4结果:" & GetLastRow_Method4(ws)
Debug.Print "方法5结果:" & GetLastRow_Method5(ws)
End Sub
不同方法的特点和适用场景:
1.
单列查找法(方法
1
)
优点:简单高效
缺点:依赖特定列数据的完整性
适用:数据列明确且连续的单列数据
2.UsedRange
法(方法
2
)
优点:自动识别数据区域
缺点:可能包含格式化的空单元格
适用:规范的数据表且无多余格式
3.
多列校验法(方法
3
)
优点:避免单列数据不完整
缺点:需要提前知道关键列
适用:多列数据长度不一致的情况
4.Find
方法(方法
4
)
优点:最全面准确
缺点:代码稍复杂
适用:需要绝对准确结果的场景
5.SpecialCells
法(方法
5
)
优点:执行速度快
缺点:可能受残留格式影响
适用:需要快速估算的场景
注意事项:
1.
如果工作表存在隐藏行或筛选,建议先取消筛选再获取
2.
处理空工作表时需加入错误处理(如方法
5
所示)
3.
数据包含公式返回空值时,建议结合
xlValues
参数使用
4.
定期使用
ws.UsedRange
重置
LastCell
位置可提高方法
5
准确性
根据实际数据特点选择最合适的方法,通常推荐方法
4
(