VBA:运行时错误'91'?

sup*_*tah 12 vba

我在这里尝试做的就是保存对当前活动窗口的引用,但它似乎不起作用.它在最后一行给出了运行时错误.

Dim SourceWindow As Window, QACheckWindow As Window
SourceWindow = ActiveWindow
Run Code Online (Sandbox Code Playgroud)

我不确定为什么.是不是ActiveWindow应该返回当前活动的窗口?如果没有,我该如何引用它?

编辑:以上是我的功能的开头,所以它之前都有 Sub FuncName()

Mat*_*don 24

在VB中,对象变量需要Set分配关键字.作为对象的对象属性也需要Set.当赋值不使用该关键字时,将引发运行时错误91"对象变量未设置".

这是继承自legacy Let关键字以分配,而Set关键字用于分配引用 ; 在Let最终被弃用(尽管仍然需要定义属性)和Set留,留下VB6/VBA赋值语法一样[Let] variable = value,其中"让"是可选的.

在声明和作业中:

Dim SourceWindow As Window, QACheckWindow As Window
'this is like saying "Let SourceWindow = ActiveWindow":
SourceWindow = ActiveWindow
Run Code Online (Sandbox Code Playgroud)

SourceWindow是一个对象,分配好像它是一个 - 因此错误.

访问非设置对象时也会引发此错误; .net等价物将是NullReferenceException:

Dim SourceWindow As Window, Dim WindowTitle As String
'"SourceWindow" reference isn't set, the object can't be accessed yet:
WindowTitle = SourceWindow.Caption 
Run Code Online (Sandbox Code Playgroud)

我将在这里略微过分,但遗留Let 语句不应与Let 子句(在VB.net中)混淆,在LINQ 查询语法(在VB.net中),它计算一个值并将其分配给新的查询范围变量(示例来自MSDN):

From p In products 
Let Discount = p.UnitPrice*0.1 '"Discount" is only available within the query!
Where Discount >= 50
Select p.ProductName, p.UnitPrice, Discount
Run Code Online (Sandbox Code Playgroud)

VB.net分配引用,而不需要指定a Let或a Set,因为在.net中,这个区别是一个更薄的行,给出了最终来自System.Object...包括的所有内容System.ValueType.这就是为什么Set关键词在VB.net也被弃用,并且也是为什么定义属性VB.net语法已经下降了Let赞成Set.