mardi 20 mars 2018

VBA IF statement Loop If values are equal

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

This code searches for a date range in cell (Column)B9 & C9 & (Row)F17 and puts the value from W2 in the range where all these meet. The issue occurs when B9&C9 contain the same date, the if statement loops until i get a 400 error.

I'm looking for a way that when B9&C9 equal each other, it still runs the code and puts the value from "W2" into where the only B9&F17 intersect with each other. The only way i know how to do this, is check if the ranges equal each other at the start of the code, then copy a similar version of what i have without:

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

Is there a more efficient way to do this, without copying the full code again and using GoTo.

Sorry guys, im quite new to VBA... Any help will me greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire