excel vba中的对象变量和With块未设置错误
Posted
技术标签:
【中文标题】excel vba中的对象变量和With块未设置错误【英文标题】:Object Variable and With block not set error from excel vba 【发布时间】:2017-07-18 15:46:59 【问题描述】:我有以下代码,但 excel 给我错误 91: Object Variable or With block variable not set error
它特别突出了我设置 lr1 等于查找公式的行。
我不知道它为什么这样做。
请。救命!
代码如下:
'Start Argument
'This Argument will deal with locating the last empty row and inserting Free Rent & Recoveries Headers
Sub LER()
'The variable lr1 is set as a Long Number
Dim lr1 As Long
'The variable lc1 is set as a Long Number
Dim lc1 As Long
'The variable sr1 is set as a Long Number
Dim sr1 As Long
Sheets("Sheet1").Range("A1").Activate
'The variable lr1 is used to store the find formula to locate the last row of cells containing any data
lr1 = Cells.Find(What:="*", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
'The variable sr1 is used to go to the truly last row of empty cells with no data whatsoever.
'This is always after the last row of cells with data, hence the "lr1 + 1" formula utilization
sr1 = lr1 + 1
'Cells from the last empty row in coloumns A through G are selected to be merged and centered
Union(Cells(sr1, 1), Cells(sr1, 2), Cells(sr1, 3), Cells(sr1, 4), Cells(sr1, 5), Cells(sr1, 6), Cells(sr1, 7)).Select
MsgBox "The last Cell is:" + sr1
'End of Argument
End Sub
【问题讨论】:
可能意味着它没有找到任何东西,因此将 lr1 分配给 Nothing 行。 【参考方案1】:将对象限定为父对象:
Dim ws1 as Worksheet
Set ws1 = Worksheets("Sheet1")
With ws1
Dim rLastCell as Range
Set rLastCell = .Cells.Find(What:="*", After:=.Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
Dim lr1 as Long
lr1 = rLastCell.Row
'... more code
End With
【讨论】:
感谢您的帮助!效果很好!以上是关于excel vba中的对象变量和With块未设置错误的主要内容,如果未能解决你的问题,请参考以下文章
解决 Excel VBA 文本文件导出中的运行时 91 错误