Home » excel » Excel VBA script: Crash on End If

Excel VBA script: Crash on End If

Posted by: admin May 14, 2020 Leave a comment

Questions:

Details:
In this segment, I am filling the cell referenced by ‘z’ with modified date values from cell referenced by ‘a’, depending on the conditions met. The code crashes at the inner End If line.

Code snippet:

    If Range(x).Value =1 Then
        If Day(Range(a)) > Day(Range(b)) Then
           Range(z).Value = DateSerial(Year(Range(a)), Month(Range(a)), Day(Range(a)-1)) + TimeSerial(20,0,0)
        Else
           Range(z).Value = DateSerial(Year(Range(a)), Month(Range(a)), Day(Range(a))) + TimeSerial(20,0,0)
        End If
    ElseIf Range(y).Value =1 Then
        Range(z).Value = DateSerial(Year(Range(a)), Month(Range(a)), Day(Range(a)-1)) + TimeSerial(8,0,0)
    Else
        Range(z).Value = Range(a).Value
    End If
How to&Answers:

Your code is good. Either you have a problem where one of your ranges is pointing to invalid data, or you have corruption in your module.

You can handle corruption by exporting your moodules to a text file (right click module in VBA editor->export) and then import into a clean workbook.

Answer:

It seems to test fine for me.

I know default properties have been created in order to make code more concise, and I realize objects should not need to be fully qualified with their parent objects but I don’t always trust the VBA compiler so my version is a little longer than yours (I’ve used the cells C1 to C5 to test):

Option Explicit

Sub FullyQualified()

With Excel.ThisWorkbook.Sheets("Sheet1")
    If .Range("C1").Value = 1 Then
        If Day(.Range("C3").Value) > Day(.Range("C4").Value) Then
           .Range("C5").Value = DateSerial(Year(.Range("C3").Value), Month(.Range("C3").Value), Day(.Range("C3").Value - 1)) + TimeSerial(20, 0, 0)
        Else
           .Range("C5").Value = DateSerial(Year(.Range("C3").Value), Month(.Range("C3").Value), Day(.Range("C3").Value)) + TimeSerial(20, 0, 0)
        End If
    ElseIf .Range("C2").Value = 1 Then
        .Range("C5").Value = DateSerial(Year(.Range("C3").Value), Month(.Range("C3").Value), Day(.Range("C3").Value - 1)) + TimeSerial(8, 0, 0)
    Else
        .Range("C5").Value = .Range("C3").Value
    End If
End With

End Sub