我希望VBA将细胞(y,x)与细胞(y,x-3)进行比较。 x应该是从第35列到第2列。但是,如果我将x定义为'对于x = 35到2步-3,vba将具有应用程序定义或对象定义的'错误。如果我将x定义为'对于x = 35至5,步骤-3'代码工作正常,但它将跳过第2列的计算。如何在这里解决问题?这是代码。
Sub testing1()
Dim x As Integer
Dim y As Integer
For x = 35 To 5 Step -3
For y = 11 To 76 Step 1
If IsNumeric(Cells(y, x).Value) Then
If VBA.Abs(Cells(y, x).Value) < VBA.Abs(0.9 * Cells(y, x - 3).Value) Or _
VBA.Abs(Cells(y, x).Value) > VBA.Abs(1.1 * Cells(y, x - 3)) Then
Cells(y, x).Interior.ColorIndex = 22
ElseIf VBA.Abs(Cells(y, x).Value) < VBA.Abs(0.9 *
Workbooks("2014variance.xlsx").Worksheets("Sheet1").Cells(y, x)) Or _
VBA.Abs(Cells(y, x).Value) > VBA.Abs(1.1 *
Workbooks("2014variance.xlsx").Worksheets("Sheet1").Cells(y, x)) Then
Cells(y, x).Interior.ColorIndex = 42
End If
End If
Next y
Next x
End Sub
答案 0 :(得分:0)
当x = 2时,x = 3 = -1。没有列-1。这就是您收到错误的原因 - Excel Application
在x = 2时使用Cells(y,x-3)
时无法返回任何单元格。
如果您希望在Cells(y,x-3))
的情况下将涉及x=2
的部分视为false,而不是抛出错误,那么您需要另一个条件来以不同的方式处理x=2
的情况。类似的东西:
For x = 35 To 2 Step -3
For y = 11 To 76 Step 1
If IsNumeric(Cells(y, x).Value) Then
If x > 2 Then
If Abs(Cells(y, x).Value) < Abs(0.9 * Cells(y, x - 3).Value) Or _
Abs(Cells(y, x).Value) > Abs(1.1 * Cells(y, x - 3)) Then
Cells(y, x).Interior.ColorIndex = 22
ElseIf Abs(Cells(y, x).Value) < Abs(0.9 * Workbooks("2014variance.xlsx").Worksheets("Sheet1").Cells(y, x)) Or _
Abs(Cells(y, x).Value) > Abs(1.1 * Workbooks("2014variance.xlsx").Worksheets("Sheet1").Cells(y, x)) Then
Cells(y, x).Interior.ColorIndex = 42
End If
Else 'x = 2 case
If Abs(Cells(y, x).Value) < Abs(0.9 * Workbooks("2014variance.xlsx").Worksheets("Sheet1").Cells(y, x)) Or _
Abs(Cells(y, x).Value) > Abs(1.1 * Workbooks("2014variance.xlsx").Worksheets("Sheet1").Cells(y, x)) Then
Cells(y, x).Interior.ColorIndex = 42
End If
End If
End If
Next y
Next x
可能有一些方法可以更优雅地表达这一点,虽然VBA缺乏短路评估,因此无法制定某些子表达式未定义的条件,因此这可能是最好的。
我将VBA.Abs()
替换为Abs()
,因为我不知道您需要告诉VBA如何查找Abs
。