我的Sheet1
包含前6行x 5列中的数据。
我添加了CommandButton
来操作此数据,但当我尝试使用Sheet1.UsedRange
时,它返回的是Range
,即121行x 44列。
我在Sheet1
中检查了该单元格,但它不包含任何数据。
为什么Sheet1.UsedRange
很奇怪?有工作吗?
编辑:
我在这两种方式中使用Sheet1.UsedRange
:
Set rng = Sheet1.UsedRange.Rows(aCell.Row)
For Each C in Sheet1.UsedRange
我唯一的希望是复制这些巨大的Find
陈述吗?
答案 0 :(得分:1)
除了评论之外,这是你正在尝试的吗?
Sub Sample()
Dim ws As Worksheet
Dim lCol As Long, rw As Long
'~~> Change this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
rw = 2 '<~~ Known row
'~~> Find the last column which has data in that row
lCol = .Cells(rw, .Columns.Count).End(xlToLeft).Column
'~~> Address of known row which has data
Debug.Print .Range("A" & rw & ":" & ReturnName(lCol) & rw).Address
End With
End Sub
'~~> Function to return Column letter from column number
Function ReturnName(ByVal num As Integer) As String
ReturnName = Split(Cells(, num).Address, "$")(1)
End Function
如果您想将其设置为范围,那么就像这样
Sub Sample()
Dim ws As Worksheet
Dim lCol As Long, rw As Long
Dim rng As Range
Dim sAddress As String
'~~> Change this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
rw = 2 '<~~ Known row
'~~> Find the last column which has data in that row
lCol = .Cells(rw, .Columns.Count).End(xlToLeft).Column
'~~> Address of known row which has data
sAddress = .Range("A" & rw & ":" & ReturnName(lCol) & rw).Address
'~~> Set Range
Set rng = .Range(sAddress)
End With
End Sub
'~~> Function to return Column letter from column number
Function ReturnName(ByVal num As Integer) As String
ReturnName = Split(Cells(, num).Address, "$")(1)
End Function
跟进评论
Sub Sample()
Dim ws As Worksheet
Dim lCol As Long, rw As Long
Dim rng As Range
'~~> Change this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
rw = 2 '<~~ Known row
'~~> Find the last column which has data in that row
lCol = .Cells(rw, .Columns.Count).End(xlToLeft).Column
'~~> Set Range
Set rng = .Range(.Cells(rw, 1), .Cells(rw, lCol))
Debug.Print rng.Address
End With
End Sub
答案 1 :(得分:-1)
Excel似乎保留了有关已经使用的范围的信息,而不仅仅是现在正在使用的部分。
这应该可以解决问题:
Dim oRng as Range
WIth Sheets(1)
Set oRng = .Range(.Range("A1").End(xlDown), .Range("A1").End(xlToRight))
End With