VBA 如何创建一个 If 来关闭已打开的文件
在宏的末尾,我有一些函数可以关闭您填写的 fuulator 的打开工作表。然而,有时其中之一不会在那里。假设 data_wb1 尚未启动。当宏完成时,它显示错误:必需的对象。这里如果不是 data_wb1 就什么都没有
If Not data_wb2 Is Nothing Then
data_wb2.Close True
Else
End If
If Not data_wb1 Is Nothing Then
data_wb1.Close True
Else
End If
If Not data_wb Is Nothing Then
data_wb.Close True
Else
At the end of the macro, I have functions that close the open sheets of the fumulators you fill out. However, sometimes one of them will not be there. Let's say data_wb1 has not been started. When the macro finishes, it shows me error : Required object. here If Not data_wb1 Is Nothing Then
If Not data_wb2 Is Nothing Then
data_wb2.Close True
Else
End If
If Not data_wb1 Is Nothing Then
data_wb1.Close True
Else
End If
If Not data_wb Is Nothing Then
data_wb.Close True
Else
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,要么您不使用 Option Explicit 且从未声明变量(因此 VBA 隐式将其动态创建为 Variant),要么您将其声明为 Variant
工作簿
。现在变体可以是任何东西,数字、日期、对象。如果您没有为 Variant 分配任何内容,则它的初始值为
Empty
。当您使用
Set
命令时,对象变量(例如Workbook类型)指向对象。通常,这被称为它获取对其的引用。声明时,它的初始值为Nothing
,这意味着它不指向对象。现在您需要区分
Empty
和Nothing
。检查Nothing
。您需要一个对象变量,否则您将收到需要对象运行时错误。对于您的情况:
(a) 使用显式选项(总是!)
(b) 将您的变量(data_wb、data_wb1、data_wb2)声明为
Workbook
这应该可以解决您的问题
注意:您应该仅在必要时使用 Variant,在您的情况下我不这样做认为没有必要)。但如果您坚持使用 Variants,则可以为它们分配
Nothing
。在这种情况下,它们不再是
空
,并且 VBA 运行时了解您正在处理对象引用,并且它们当前不指向任何内容。Problem is that either you don't use
Option Explicit
and never declared the Variable (so VBA implicitly creates it on the fly as Variant), or you declared it asVariant
instead ofWorkbook
.Now a Variant can be anything, a Number, a Date, an Object. If you don't assign anything to a Variant, it has it's initial value which is
Empty
.An Object Variable (eg of type Workbook) points to an Object when you use the
Set
-command. Usually, this is called It gets a reference to it. When declared, it's initial value isNothing
which means it doesn't point to an object.Now you need to distinguish between
Empty
andNothing
. To check forNothing
. you need an Object Variable, else you will get the Object required runtime error.In your case:
(a) Use Option Explicit (always!)
(b) Declare your variables (data_wb, data_wb1, data_wb2) as
Workbook
That should solve your problem
Note: You should use Variant only if necessary and in your case I don't think it's necessary). But if you insist in using Variants, you can assign
Nothing
to them.In that case, they are no longer
Empty
and the VBA runtime understands that you are dealing with Object references and that they currently don't point to anything.