尝试重新初始化时运行时错误1004“应用程序定义或对象定义的错误”

我正在尝试运行一个简单的VBA excel脚本。 有一点,我需要将variables设置回零。 如果我尝试这样做,我正在尝试重新初始化variablesans时出现错误“VBA运行时错误1004”应用程序定义或对象定义的错误“我做错了什么?

Sub macro1() Dim row As Integer Dim trial As Integer Dim ans As Integer Dim amp As Double row = 48 trial = 25 ans = 0 amp = 0 Do While Cells(row, 2) <> "" If Cells(row, 2).Value = trial Then If Cells(row, 21).Value > amp Then ans = row amp = Cells(row, 21).Value row = row + 1 Debug.Print (amp) Else row = row + 1 End If Else Cells(ans, 39).Value = amp row = row + 1 trial = trial + 1 ans = 0 // Problem in this line End If Loop End Sub 

问题实际上发生在这一行上:

 Cells(ans, 39) = amp 

原因是因为ans的值是0,并且单元格不是“零索引”的。 第一行是1,而不是0。

尝试初始化1,而不是0:

 Sub Macro1() Dim row As Integer Dim trial As Integer Dim ans As Integer Dim amp As Double row = 48 trial = 25 ans = 1 amp = 1 Do While Cells(row, 2) <> "" If Cells(row, 2).Value = trial Then If Cells(row, 21).Value > amp Then ans = row amp = Cells(row, 21).Value row = row + 1 Debug.Print (amp) Else row = row + 1 End If Else Cells(ans, 39) = amp row = row + 1 trial = trial + 1 ans = 1 End If Loop End Sub