代码如下所示。
运行时错误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
这个问题可能是你没有初始化的全局变量:
Public wb As Workbook
Private rowMsg As Long '<-- needs to be long not integer.
如果你再运行showMsg
首次wb
是Nothing
和rowMsg
是0
(这不是有效的行数,因为它与行= 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
只有三个在你列出的程序对象:WB,工作表名为“设置”,由Rowmsg定义的小区。为了得到错误在此房源这三个中的一个不存在。要么不存在所谓的“设置”工作表,工作簿对象指向WB不存在或(这是最像)可变RowMsg适用于你正在它的使用无效值。在猜测你使用查找设置的行数,当它没有找到一个结果出现错误。
当你的错误选择调试和检查报告该错误的行。然后,您可以使用“查看,调用堆栈”中的VB编辑器通过你们的节目,看后退一步什么未能正确设置变量