我需要找出定义为范围内最后一列的列:
Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange
第一件事
永远不要UsedRange
用来设置你的范围。我已经在这里解释了为什么你不应该使用UsedRange
Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange
找到有数据的最后一列和有数据的最后一行,然后设置你的范围。因此,不会出现从范围中查找最后一列的问题。这是一个例子
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Dim lRow As Long, lCol As Long
'~~> Set your worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
'~~> Find Last Row
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
'~~> Find Last Column
lCol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Else
lRow = 1: lCol = 1
End If
'~~> Set your range
Set rng = .Range(.Cells(1, 1), .Cells(lRow, lCol))
Debug.Print rng.Address
End With
End Sub
将 End(xlToRight) 与活动单元一起使用。