excel - 如何解决错误对象变量或未设置块变量?
问题描述
代码如下。
运行时错误 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
isNothing
并且rowMsg
is 0
(这不是有效的行号,因为它以 row = 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
推荐阅读
- python - CX_Oracle - 将特定模式中的 Oracle 数据导入 Pandas 数据框
- java - 为什么在 junit5 测试中自动连线控制器总是为空?
- java - 为什么多对一关系中的 Hibernate FetchType.EAGER 或 fetch = FetchType.LAZY 会中断
- microsoft-teams - Microsoft Teams API 响应无法显示中文/日文
- r - R-Studio csv 导入以逗号分隔,但在某些字符串中包含分号
- ios - 如何在 PromiseKit 6 中使用循环?
- angular - 如何以最大并行请求数发送 1000 个 XHTTP 请求
- wcf - WCF SOAP 服务给出错误接收到 http://localhost/Service1.svc 的 HTTP 响应时发生错误
- java - 局部变量在使用前未分配异常
- java - 为什么我不能在一行中加入 FileReader 和 System.out.println?