关闭工作簿时出现“未设置对象变量或带块变量”

时间:2019-08-15 06:58:25

标签: excel vba

我正在尝试修复一些代码,但是没有使用Microsoft Visual Basic的经验。关闭活动工作簿时,出现运行时错误“ 91”,导致该错误的代码为:

Set appExcel = New Excel.Application
appExcel.Visible = True

' More VBA code here, I can post if it would be necessary but I would 
' assume this is enough code to see the problem

appExcel.ActiveWorkbook.Close
appExcel.Quit

我假设此时Excel活动工作簿将关闭并且不知道为什么此代码未执行此操作

1 个答案:

答案 0 :(得分:1)

您收到该错误,因为那时该实例中没有打开工作簿

如果您尝试使用此代码,将会看到您不会收到错误消息

Set appExcel = CreateObject("Excel.Application")
appExcel.Visible = True

'
'~~> Rest of the code
'
appExcel.Workbooks.Add '<~~ Add a temp workbook
appExcel.ActiveWorkbook.Close

要处理此问题

Set appExcel = CreateObject("Excel.Application")
appExcel.Visible = True

'
'~~> Rest of the code
'
If appExcel.Workbooks.Count > 0 Then appExcel.ActiveWorkbook.Close

最好使用Objects,以免错误地关闭错误的工作簿。例如

Dim wb As Workbook
Set wb = appExcel.Workbooks.Add
'
'~~> Rest of the code
'
If Not wb Is Nothing Then wb.Close
Set wb = Nothing