VBA中能否在With代码块内调用函数?如何引用父对象解决报错?
问题解答:在VBA With块内调用函数的正确姿势
当然可以在With代码块里调用函数!你遇到的"invalid or unqualified reference"错误,核心原因是VBA的With上下文不会自动传递给外部函数——你的LastRow函数里用了.Cells,但这个点号没有对应的父对象(函数不知道你指的是哪个工作表),所以才会报错。
解决思路
把With块中的目标对象(也就是当前工作表)作为参数传递给LastRow函数,让函数明确知道要操作哪个工作表。同时,还要处理工作表为空的边界情况(避免Find返回Nothing时崩溃)。
修正后的完整代码
Option Explicit ' 一定要加,强制变量声明,避免隐性错误 Sub Test() Dim wb As Workbook Dim lRow As Long Set wb = Workbooks.Open("C:\Book1.xls", True, True) With wb.Worksheets("Sheet1") lRow = LastRow(.) ' 把With块的当前工作表传给函数 MsgBox lRow End With With wb.Worksheets("Sheet2") lRow = LastRow(.) MsgBox lRow End With wb.Close False End Sub Function LastRow(ws As Worksheet) As Long Dim lastCell As Range Set lastCell = ws.Cells.Find(What:="*", _ After:=ws.Range("A1"), _ LookAt:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False) ' 处理空表的情况 If Not lastCell Is Nothing Then LastRow = lastCell.Row Else LastRow = 1 ' 空表返回第1行,或者根据需求改成0 End If End Function
关键细节说明
Option Explicit:强制所有变量必须声明,能帮你避免很多隐性错误(比如变量名拼写错误)。- 函数参数
ws As Worksheet:明确指定操作的工作表,彻底解决“未限定引用”的问题。 - 空表判断:如果工作表完全为空,
Find会返回Nothing,直接取.Row会触发运行时错误,所以必须加判断。 - With块内传参:用
.代表当前With块的对象(这里就是目标工作表),简洁又准确。
内容的提问来源于stack exchange,提问作者Helloguys
相关产品推荐
相关产品推荐

