gpt4 book ai didi

Excel.Application.Cells.SpecialCells(xlCellTypeLastCell) 返回工作表的底部,而不是最后一个数据单元格

转载 作者:行者123 更新时间:2023-12-01 19:16:55 28 4
gpt4 key购买 nike

我正在 Excel 2013 中的 VBA 中编写一个方法来遍历两个工作表中的行并比较每个工作表中的一列中的文本。当我运行我的代码时,我发现代码循环遍历整个工作表,而不仅仅是包含数据的行。
Excel.Sheets("Sheet1").Cells.SpecialCells(xlCellTypeLastCell)返回正确列中的单元格,但该行是工作表中的最后一行 (1048576),而不是包含数据的最后一行 (1951)。

我写了一个空单元格检查(因为我不能确定有效范围内的每一行都被使用了),所以它不会导致任何错误,但是因为这个方法是从内部调用的 Worksheet_Change ,它确实减慢了速度。

通常,当错误报告“最后一个”单元格时,保存通常会修复它,如果没有,则将错误报告的最后一个单元格中的行(不仅仅是内容,而是整个行)删除回实际的最后一个单元格,然后保存作品。但是,在这种情况下,它没有帮助。

我用谷歌搜索没有成功。我不想将所有数据和代码从这个工作簿复制到一个新的工作簿中。有任何想法吗?

最佳答案

(信息太多,无法在此处使用评论。)

VBA 策划者 Ron de Bruin 写了一点关于为什么 xlCellTypeLastCell以及 UsedRange可能在这里失败:http://www.rondebruin.nl/win/s9/win005.htm .

(在我最初评论中链接到的帖子 Error in finding last used cell in VBA 中,UsedRange 的陷阱以相同的方式描述。)

这是直接报价:

Possible problems with xlCellTypeLastCell and UsedRange are:

The last cell will only re-set when you save (or save/close/reopen the file). If cell formatting is changed it will not reset the last cell, clearing the data is not enough, you must delete the rows or columns then, See: http://www.contextures.com/xlfaqApp.html#Unused



长话短说,在工作表上查找最后一行的逻辑属于全局函数。您将一直使用此功能。这是查找工作表上最后一行的示例:
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'INPUT : Sheet, the worksheet we'll search to find the last row
'OUTPUT : Long, the last occupied row
'SPECIAL CASE: if Sheet is empty, return 1
'EXAMPLES :
'
'assume that there is a single
'entry on MySheet in cell A5:
'
'LastRowNum(MySheet)
'>> 5
'
'assume that EmptySheet is totally empty:
'
'LastRowNum(EmptySheet)
'>> 1
'
Public Function LastRowNum(Sheet As Worksheet) As Long
If Application.WorksheetFunction.CountA(Sheet.Cells) <> 0 Then
LastRowNum = Sheet.Cells.Find(What:="*", _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
Else
LastRowNum = 1
End If
End Function

就否决票而言——不知道。我实际上从来没有在这里投票过哈哈。

关于Excel.Application.Cells.SpecialCells(xlCellTypeLastCell) 返回工作表的底部,而不是最后一个数据单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25110873/

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