VBA IF语句循环如果值相等

时间:2018-03-20 10:22:21

标签: excel vba for-loop if-statement

Sub DataEntry()

Dim col, ro, col2 As Double
Dim sCellVal As String
col = 0
col2 = 0
ro = 0

Dim cel As Range


sCellVal = Range("D9").Value


If sCellVal Like "Night" Then


For Each cel In Worksheets("Service").Range("C40:NR40")


If cel.Value = Range("B9").Value Then
col = cel.Column

ElseIf cel.Value = Range("C9").Value Then
col2 = cel.Column
Exit For
End If

Next cel


If col = 0 Then
MsgBox "Date Not Found"
Exit Sub
End If


For Each cel In Worksheets("Service").Range("A40:A80")


If cel.Value = Range("F17").Value Then
ro = cel.Row
Exit For
End If


Next cel


If ro = 0 Then
MsgBox "Name Not Found"
Exit Sub
End If


With Worksheets("Service")
.Range(.Cells(ro, col), .Cells(ro, col2)).Value = Range("W2").Value
End With


MsgBox "Record added (Night Pay)"


Exit Sub
End If


For Each cel In Worksheets("Service").Range("C1:NR1")

If cel.Value = Range("B9").Value Then
col = cel.Column

ElseIf cel.Value = Range("C9").Value Then
col2 = cel.Column

Exit For
End If

Next cel


If col = 0 Then
MsgBox "Date Not Found"
Exit Sub
End If


For Each cel In Worksheets("Service").Range("A1:A40")


If cel.Value = Range("F17").Value Then
ro = cel.Row
Exit For
End If


Next cel


If ro = 0 Then
MsgBox "Name Not Found"
Exit Sub
End If

With Worksheets("Service")
.Range(.Cells(ro, col), .Cells(ro, col2)).Value = Range("W2").Value
End With


MsgBox "Record added!"


End Sub

此代码在单元格(列)B9&中搜索日期范围。 C9& (行)F17并将W2中的值放在所有这些符合的范围内。当B9和C9包含相同的日期时,问题就出现了,if语句循环直到我得到400错误。

我正在寻找一种方式,当B9和C9彼此相等时,它仍会运行代码并将值从" W2"到唯一的B9和F17相互交叉的地方。我知道如何执行此操作的唯一方法是检查代码开头是否相等,然后复制我所拥有的类似版本:

    ElseIf cel.Value = Range("C9").Value Then
col2 = cel.Column
Exit For
End If

有没有更有效的方法来执行此操作,而无需再次复制完整代码并使用GoTo。

对不起伙计们,我对VBA很新...任何帮助都会让我非常感激。

1 个答案:

答案 0 :(得分:0)

似乎你应该删除ElseIf并使用两个或可能三个独立的If语句。

col = 0: col2 = 0

For Each cel In Worksheets("Service").Range("C40:NR40")

    If cel.Value = Range("B9").Value Then col = cel.Column

    If cel.Value = Range("C9").Value Then col2 = cel.Column

    if col<>0 and col2<>0 then exit for

Next cel