pjj*_*pjj 48 .net vb.net excel vba excel-interop
列A包含这样的数据(即频繁的空白单元格):
HEADING <-- this is A1
kfdsl
fdjgnm
fdkj
gdfkj
4353
fdjk <-- this is A9
Run Code Online (Sandbox Code Playgroud)
我希望能够获得具有数据的最后一个单元格的单元格引用.所以在上面的例子中我想返回:A9
我试过这个,但它停在第一个空白区(即返回A4)
numofrows = destsheet.Range("A2").End(xlDown).Row - 1
Run Code Online (Sandbox Code Playgroud)
小智 49
我喜欢这样:
ActiveSheet.UsedRange.Rows.Count
列数可以完成相同的操作.对我来说,总是工作.但是,如果您在其他列中有数据,上面的代码也会考虑它们,因为代码正在查找工作表中的所有单元格范围.
nix*_*xda 41
最安全的选择是
Lastrow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
Lastcol = Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column
Run Code Online (Sandbox Code Playgroud)
不要使用UsedRange或SpecialCells(xlLastCell)或End(xlUp).如果您之前删除了某些行,则所有这些方法都可能会产生错 Excel仍会计算这些不可见的单元格.
如果删除单元格,保存工作簿,关闭并重新打开它们,这些方法将再次起作用.
Jea*_*ett 26
这将工作,独立于Excel版本(2003年,2007年,2010年).第一个在一张纸上有65536行,而后两个有一百万行左右.Sheet1.Rows.Count根据版本返回此数字.
numofrows = Sheet1.Range("A1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp).Row
Run Code Online (Sandbox Code Playgroud)
或相当但更短的
numofrows = Sheet1.Cells(Sheet1.Rows.Count,1).End(xlUp)
Run Code Online (Sandbox Code Playgroud)
这将从A列的底部向上搜索第一个非空单元格,并获取其行号.
如果您的数据在其他列中更进一步,这也适用.因此,例如,如果您获取示例数据并在单元格FY4763中写入内容,则上述内容仍将正确返回9(不是4763,任何涉及该UsedRange属性的方法都会错误地返回).
请注意,实际上,如果您需要单元格引用,则应该使用以下内容.您不必先获取行号,然后构建单元格引用.
Set rngLastCell = Sheet1.Range("A1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp)
Run Code Online (Sandbox Code Playgroud)
请注意,此方法在某些边缘情况下失败:
因此,请注意您是否计划使用1,048,576行进行这些操作!
小智 19
我用长测试表比较了所有可能性:
0,140625秒
lastrow = calcws.Cells.Find("*", [A1], , , xlByColumns, xlPrevious).row
Run Code Online (Sandbox Code Playgroud)
0秒
iLastRow = calcws.Cells(rows.count, "a").End(xlUp).row
Run Code Online (Sandbox Code Playgroud)
和
numofrows = calcws.Cells.SpecialCells(xlLastCell).row
Run Code Online (Sandbox Code Playgroud)
0,0078125秒
lastrow = calcws.UsedRange.rows.count
Do While 1
If calcws.Cells(lastrow, 1).Value = "" Then
lastrow = lastrow - 1
Else
Exit Do
End If
Loop
Run Code Online (Sandbox Code Playgroud)
我认为最喜欢的是......
在另一个站点上找到此方法.它适用于新的较大尺寸的Excel,不需要您对最大行数和列数进行硬编码.
iLastRow = Cells(Rows.Count, "a").End(xlUp).Row
iLastCol = Cells(i, Columns.Count).End(xlToLeft).Column
Run Code Online (Sandbox Code Playgroud)
这些都可以,让 Excel 定义它最后一次看到数据的时间
numofrows = destsheet.UsedRange.SpecialCells(xlLastCell).row
numofrows = destsheet.Cells.SpecialCells(xlLastCell).row
Run Code Online (Sandbox Code Playgroud)