将单元格与列中的上一个单元格进行比较,并根据差异

时间:2016-04-13 23:28:20

标签: excel vba if-statement macros

Sub Update_cell()

Dim counter As Integer
For counter = 7 To 606
   If Worksheets("Sheet1").Cells(counter + 1, 4).Value > (Worksheets("Sheet1").Cells(counter, 4).Value + Worksheets("Sheet1").Cells(1, 1).Value) Then
   Worksheets("Sheet1").Cells(counter, 4).Value = (Worksheets("Sheet1").Cells(counter, 4).Value + Worksheets("Sheet1").Cells(1, 1).Value)
   Worksheets("Sheet1").Cells(counter + 1, 4).Value = Worksheets("Sheet1").Cells(counter + 1, 4).Value - 1 * (Worksheets("Sheet1").Cells(counter + 1, 4).Value - Worksheets("Sheet1").Cells(counter, 4).Value)
   Worksheets("Sheet1").Cells(counter, 13).Value = -1 * (Worksheets("Sheet1").Cells(counter + 1, 4).Value - Worksheets("Sheet1").Cells(counter, 4).Value)
   End If
   If Worksheets("Sheet1").Cells(counter + 1, 4).Value < (Worksheets("Sheet1").Cells(counter, 4).Value - Worksheets("Sheet1").Cells(1, 1).Value) Then
   Worksheets("Sheet1").Cells(counter, 4).Value = (Worksheets("Sheet1").Cells(counter, 4).Value - Worksheets("Sheet1").Cells(1, 1).Value)
   Worksheets("Sheet1").Cells(counter + 1, 4).Value = Worksheets("Sheet1").Cells(counter + 1, 4).Value - 1 * (Worksheets("Sheet1").Cells(counter + 1, 4).Value - Worksheets("Sheet1").Cells(counter, 4).Value)
   Worksheets("Sheet1").Cells(counter, 13).Value = -1 * (Worksheets("Sheet1").Cells(counter + 1, 4).Value - Worksheets("Sheet1").Cells(counter, 4).Value)
   End If
   If Worksheets("Sheet1").Cells(counter + 1, 4).Value <= (Worksheets("Sheet1").Cells(counter, 4).Value + Worksheets("Sheet1").Cells(1, 1).Value) And Worksheets("Sheet1").Cells(counter + 1, 4).Value >= (Worksheets("Sheet1").Cells(counter, 4).Value - Worksheets("Sheet1").Cells(1, 1).Value) Then
   Worksheets("Sheet1").Cells(counter, 4).Value = Worksheets("Sheet1").Cells(counter + 1, 4).Value
   End If
   Next counter
End Sub

上面是我的代码,我用它来根据它与前一个单元格的距离来更新单元格。在开始时,我收到一条错误消息“指定的维度对当前图表类型无效”。我删除了已经存在的图表,现在我收到错误说“下标超出范围,运行时错误9”。当我尝试调试时,它会突出显示第一个If语句。

非常感谢任何帮助。非常感谢你!

1 个答案:

答案 0 :(得分:0)

@Scott Craner在评论部分提供了我的问题的答案。我使用Sheet1作为工作表名称而不是工作表的实际名称。下次应该更加小心。

再次感谢斯科特!