【问题标题】:Multiple delaration of objects, they set "empty"对象的多个声明,它们设置为“空”
【发布时间】:2019-09-17 08:11:01
【问题描述】:

我设置了多个Worksheet对象,只设置了最后一个对象Nothing,第一个X是empty

多行声明正在工作

Dim ws1, ws2 As Worksheet

If ws1 is nothing then
If ws1 = "" then
If ws1 = "Empty" then
If ws1 = vbEmpty then
If IsEmpty(ws1) then
If IsNull(ws1) then

    'tried all of these but get
    'runtime error


If ws2 is nothing then

    'works fine
Dim ws1 As Worksheet, ws2 As Worksheet

If ws1 is nothing then

    'works fine

If ws2 is nothing then

    'works fine

因Pᴇʜ的回答而跟进:

Dim ws1, ws2 As Worksheet

If ws1 Is Nothing Or IsEmpty(ws1) then

    'runtime error

If IsEmpty(ws1) then

    'works fine

If ws2 Is Nothing then

    'works fine

运行时错误 424

我只是想通过多行声明使代码更干净,也许这是不可能的

结论: 我们必须分别声明每个变量! 第一个答案中的更多详细信息

【问题讨论】:

    标签: excel vba object worksheet


    【解决方案1】:

    “我设置了多个‘工作表’对象”

    不,你没有。

    如果你声明

    Dim ws1, ws2 As Worksheet
    

    那么ws2 的类型为Worksheet,但ws1 的类型为Variant,因为您没有为第一个变量指定类型。因此,ws1 不是对象,除非您将其设置为 1,而 If ws1 Is Nothing Then 会失败,因为它只能与对象一起使用。

    完全一样
    Dim ws1 As Variant, ws2 As Worksheet
    

    如果您在一行中声明多个变量(在 VBA 中),您仍然需要为 每个 变量指定一个类型(或者默认为 Variant):

    Dim ws1 As Worksheet, ws2 As Worksheet
    

    注意:
    这仅在 VBA 中有效。如果您还使用 VB.NET,请小心,因为 Dim a, b As Long 会将 both 变量定义为 Long!在 VBA 中则不然!


    跟进回答:

    以下If 声明……

    Dim ws1, ws2 As Worksheet
    If ws1 Is Nothing Or IsEmpty(ws1) then
    

    错误,因为在带有Or/And 运算符的If 语句中,无论其他测试的结果如何,总是执行所有测试。所以在这种情况下,它会同时测试ws1 Is NothingIsEmpty(ws1)

    第一个错误是因为ws1Variant 而不是对象,但Is Nothing 仅适用于对象。因此整个语句错误。

    【讨论】:

    • 好的,但是为什么下面的 if 语句会失败:``` If ws_1 Is Nothing Or IsEmty(ws_1) Then 'do something 'getting runtime error End If ```
    • @Patrick 因为Is Nothing 需要一个对象,但如果ws1Variant 它不是一个对象,因此它会失败。
    • @Patrick 在带有OrAnd 运算符的If 语句中,将执行所有 测试。如果一个错误整个If 语句错误。由于Is Nothing 错误,整个语句不起作用。
    猜你喜欢
    • 1970-01-01
    • 2011-11-18
    • 2023-04-07
    • 1970-01-01
    • 2020-11-24
    • 2016-04-21
    • 2012-07-22
    • 1970-01-01
    • 2012-03-22
    相关资源
    最近更新 更多