【发布时间】:2018-03-20 10:22:21
【问题描述】:
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
此代码在单元格 (Column)B9 & C9 & (Row)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 很陌生...任何帮助将不胜感激。
【问题讨论】:
标签: excel vba for-loop if-statement