gpt4 book ai didi

VBA:获取运行时 1004:使用单元格时对象 'Range' 的方法 '_Worksheet' 失败

转载 作者:行者123 更新时间:2023-12-02 12:38:51 24 4
gpt4 key购买 nike

我有 2 个工作表: Assets 和概述。

所有功能都放在一个模块中。

Public Function GetLastNonEmptyCellOnWorkSheet(Ws As Worksheet, Optional sName As String = "A1") As Range
Dim lLastRow As Long
Dim lLastCol As Long
Dim rngStartCell As Range

Set rngStartCell = Ws.Range(sName)
lLastRow = Ws.Cells.Find(What:="*", After:=Ws.Range(rngStartCell), LookIn:=xlFormulas, _
Lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, _
MatchCase:=False).Row

lLastCol = Ws.Cells.Find(What:="*", After:=Ws.Range(rngStartCell), LookIn:=xlFormulas, _
Lookat:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, _
MatchCase:=False).Column

Set GetLastNonEmptyCellOnWorkSheet = Ws.Range(Ws.Cells(lLastRow, lLastCol))
End Function

从工作表概述中我调用:

   Set RngAssets = GetLastNonEmptyCellOnWorkSheet(Worksheets("Assets"), "A1")

但我总是收到错误:

VBA: Getting run-time 1004: Method 'Range' of object '_Worksheet' failed

上线:

 Set GetLastNonEmptyCellOnWorkSheet = Ws.Range(Ws.Cells(lLastRow, lLastCol))

工作表 Assets 上有数据。最后使用的单元格是 W9(lLastRow = 9 且 lLastCol = 23)。

知道为什么这不起作用吗?

最佳答案

这是您的问题陈述:

Set GetLastNonEmptyCellOnWorkSheet = Ws.Range(Ws.Cells(lLastRow, lLastCol))

计算最里面的括号:

ws.Cells(lLastRow, lLastCol)

这是一个范围,但范围的默认属性是其.Value。除非存在与该值相对应的命名范围,否则会出现错误。

相反,请尝试:

Set GetLastNonEmptyCellOnWorkSheet = Ws.Range(Ws.Cells(lLastRow, lLastCol).Address)

或者你可以稍微简化一下:

Set GetLastNonEmptyCellOnWorkSheet = Ws.Cells(lLastRow, lLastCol)

关于VBA:获取运行时 1004:使用单元格时对象 'Range' 的方法 '_Worksheet' 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27802286/

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