我有这段代码,应该检查第三列中某个值4的范围,如果一个单元格具有值4,就应该检查第四列中相邻单元格的值。 如果此值小于y,则应将值4分配给第15列中的5个单元格,该单元格从最初找到4的行开始。如果它高于它,则应将其分配给第15列中的8个单元格,该单元格最初是在最初找到4个的行中开始的。
不断出现的问题是Else
部分中的单元格规范,例如.Cells(x - 1, a).Value = 5
导致错误。如果我仅使用If
部分,则效果很好。
Sub einfügen()
Dim a As Integer
Dim x As Integer
Dim y As LongLong
a = 15
y = 100000
With ActiveWorkbook.ActiveSheet
For x = 1 To 112
If .Cells(x, 3).Value = 4 And ActiveWorkbook.ActiveSheet.Cells(x, 3).Offset(0, 1) <= y Then
.Cells(x - 1, a).Value = 4
.Cells(x - 2, a).Value = 4
.Cells(x - 3, a).Value = 4
.Cells(x - 4, a).Value = 4
.Cells(x - 5, a).Value = 4
Else
.Cells(x - 1, a).Value = 4
.Cells(x - 2, a).Value = 4
.Cells(x - 3, a).Value = 4
.Cells(x - 4, a).Value = 4
.Cells(x - 5, a).Value = 4
.Cells(x - 6, a).Value = 4
.Cells(x - 7, a).Value = 4
.Cells(x - 8, a).Value = 4
End If
Next
End With
End Sub
答案 0 :(得分:0)
我不太清楚“应从最初找到4的那一行开始。” 的实际含义,所以我认为它应该从当前行x
开始向下< / p>
此外,根据您的叙述,您必须将第一个IF条件分为两个条件,否则,您的代码将始终尝试用4填充某些单元格
以下是您可能要尝试的代码段:
With ActiveWorkbook.ActiveSheet
For x = 1 To 112
If .Cells(x, 3).Value = 4 Then '" if a cell has the value 4"
If .Cells(x, 3).Offset(0, 1) <= y Then '"check the value of the adjacent cell in the fourth column. If this value is smaller than y..."
.Cells(x, a).Resize(5).Value = 4 '"assign the value 4 to the 5 cells in the 15th column starting in the row in which the 4 was initially found."
Else '"If it's higher"
.Cells(x, a).Resize(8).Value = 4 '"assign it to 8 cells in column 15 starting in the row in which the 4 was initially found."
End If
End If
Next
End With