Search code examples
excelvbaif-statementgoto

Vba Goto won't work properly


Hi all I've been playing around with "If" "Then" "And" and "Goto"

I think I got the hang of all except the "Goto" many times I can't get it to work I'm not sure if it's because I'm using the "If" wrong or it's because I use the "Goto" wrong. Can someone please take a look at this code to tell me what I am doing wrong with it. Because I use "If" statements a lot so it would be nice if I'm using it the best and right way. And yes I know in the following code that I use the activesheet and I should do the code without working with a activesheet as many people in here stats but I'm not sure yet how to use the

Columns(1).Insert Shift:=xlRight

yet without activation the sheet

So here is the code I do have cell A1 with the Value "new" so the Goto should be activated but its not.

Sub con()
Set tsheet = ThisWorkbook.Sheets("Players")
Sheets("Players").Activate
ActiveSheet.Columns(1).Insert Shift:=xlRight
Dim lngLastRow As Long
If tsheet.Range("A1") = "new" Then
GoTo AlR
Else
    lngLastRow = Cells(Rows.Count, "B").End(xlUp).Row
    Range("A2").Formula = "=B2 & "" "" & C2 & "" "" & G2 & "" "" & D2"
    Range("A2").Copy Range("A2:A" & lngLastRow)
    tsheet.Range("A1").Value = "new"
End If
AlR:
MsgBox "Column is already present"
End Sub

Solution

  • Make yourself and the future a favor: don't use GOTOs for anything else than error handling.

    What you are doing now is called Spaghetti code.

    Your code should be :

    Sub con()
    Set tsheet = ThisWorkbook.Sheets("Players")
    Sheets("Players").Activate
    ActiveSheet.Columns(1).Insert Shift:=xlRight
    Dim lngLastRow As Long
    If tsheet.Range("A1") = "new" Then 
        MsgBox "Column is already present"
    else
        lngLastRow = Cells(Rows.Count, "B").End(xlUp).Row
        Range("A2").Formula = "=B2 & "" "" & C2 & "" "" & G2 & "" "" & D2"
        Range("A2").Copy Range("A2:A" & lngLastRow)
        tsheet.Range("A1").Value = "new"
    End If
    
    End Sub