我在Msgbox系列上遇到了应用程序定义或对象定义的错误。我将两个InputBox变量声明为String。我尝试将Sheets(sheetname1)更改为实际的工作表名称但错误相同。我尝试了所有我知道的事情,我对这个错误感到困惑。任何帮助表示赞赏。
sheetname1 = Application.InputBox("Enter the name of your first sheet.")
sheetname2 = Application.InputBox("Enter the name of your second sheet.")
For i = 1 To 100
For j = 1 To 100
If Not Sheets(sheetname1).Cells(i, j).Value = Sheets(sheetname2).Cells(i, j).Value Then
Sheets(sheetname1).Select
Cells(i, j).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ans = MsgBox("Cells " & i & "," & j & " do not match." & vbNewLine & "The value on " & sheetname1 & " is " & Sheets(sheetname1).Cells(i, j).Value & " and the value on " & sheetname2 & " is " & Sheets("sheetname2").Cells(i, j).Value, vbOKCancel + vbQuestion)
If ans = vbCancel Then Exit Sub
Else
GoTo skip1
End If
skip1:
Next j
Next i
答案 0 :(得分:3)
作为@BruceWayne correctly identified,您正在使用未声明的变量。使用Option Explicit
。
让我重新说一下......
简单:将单词Option Explicit
粘贴在您看到的每个单元的顶部,VBA将拒绝编译您使用未声明变量的代码。
在这种情况下,您指的是i1
和j1
,它们都包含非值Empty
,因为它们是未声明的和未初始化的变体。
以下是您需要声明的变量:
Dim i As Long
Dim j As Long
Dim ans As vbMsgBoxResult
Dim sheetName1 As String
Dim sheetName2 As String
如果没有Option Explicit
,VBA很乐意编写拼写错误并将其视为“哦,我从未见过那个人,必须是一个新的变量!”