如何解决错误的对象变量或未设置块变量?

时间:2019-02-11 14:11:18

标签: excel vba

下面给出了代码。

  

运行时错误91对象变量或未设置块变量的情况。

它有时会完美工作,但有时会显示给定的错误。

Option Explict 

Public wb As Workbook
Private rowMsg As Integer

Public Sub showMsg(pMsg As String, Optional pColorError As Boolean,
     Optional pColorSuccessful As Boolean)

    With wb.sheets("Setup")
        .Rows(rowMsg).HorizontalAlignment = xlLeft
        .Rows(rowMsg).VerticalAlignment = xlBottom
        .Rows(rowMsg).WrapText = True
        .Rows(rowMsg).Orientation = 0
        .Rows(rowMsg).AddIndent = False
        .Rows(rowMsg).IndentLevel = 0
        .Rows(rowMsg).ShrinkToFit = False
        .Rows(rowMsg).ReadingOrder = xlContext
        .Rows(rowMsg).MergeCells = True

        .Cells(rowMsg, 1).Value = Now & Space(3) & pMsg

        If pColorSuccessful Then
            .Cells(rowMsg, 1).Interior.ColorIndex = 43
        End If
        If pColorError Then
            .Cells(rowMsg, 1).Interior.ColorIndex = 3
        End If
    End With

    rowMsg = rowMsg + 1
End Sub

2 个答案:

答案 0 :(得分:0)

问题可能是您没有初始化全局变量:

Public wb As Workbook
Private rowMsg As Long '<-- needs to be long not integer.

如果您是第一次运行showMsg,则wbNothing,而rowMsg0(这不是有效的行号,因为它是从第1行开始)。

因此,请先测试变量是否已初始化,然后再对它们运行任何代码。

Public Sub showMsg(pMsg As String, Optional pColorError As Boolean, Optional pColorSuccessful As Boolean)

    'test if global variables were initialized, if not do it.
    If wb Is Nothing Then 
        Set wb = ThisWorkbook
    End If

    If rowMsg = 0 Then rowMsg = 1

    'your code here …
End Sub

答案 1 :(得分:-1)

您列出的程序中只有三个对象:wb,名为“ Setup”的工作表和Rowmsg定义的单元格。为了得到此清单中的错误,不存在这三个之一。要么没有名为“ Setup”的工作表,要么wb指向的工作簿对象不存在,或者(这很像)变量RowMsg持有无效的值供您使用。猜测是您使用“查找”设置行号,如果找不到结果,则会发生错误。

收到错误后,选择“调试”并检查报告错误的行。然后,您可以在vb编辑器中使用“查看,调用堆栈”查看程序,以查看无法正确设置变量的原因