我的Msgbox行Excel VBA错误

我收到我的Msgbox行上的应用程序定义或对象定义的错误。 我有两个声明为String的InputBoxvariables。 我试过将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 

由于@BruceWayne正确识别 ,您正在使用未声明的variables。 使用Option Explicit

让我换个说法

总是使用Option Explicit

简单:在每个你看到的单个模块的顶部粘贴Option Explicit字样,VBA将拒绝在你使用未声明的variables的地方编译代码。

在这种情况下,您指的是i1j1 ,它们都包含非EmptyEmpty ,因为它们是未声明的和未初始化的变体。

这里是你需要声明的variables:

 Dim i As Long Dim j As Long Dim ans As vbMsgBoxResult Dim sheetName1 As String Dim sheetName2 As String 

如果没有Option Explicit ,VBA高兴地编写一个错字,并把它作为“哦,我从来没有见过这个人,必须是一个新的variables!”