简体   繁体   中英

Error handling when tab doesn't exist in Excel VBA

`Range("P" & Sheetfind).NumberFormat = "dd mmmm yyyy"tb = Range("P" & Sheetfind).Text
Workbooks.Open Filename:="\\data\Hq\Work Returns\QC\" & Selection.Value & ".xlsx", ReadOnly:=True
Sheets(tb).Select
Workbooks(usersname & ".xlsx").Activate
Set WB2 = ActiveWorkbook
' Put stuff
Range("B2:d2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ThisWorkbook.Activate
Sheets("Prep sheet").Select
Range("B" & movedown).Select
     Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheetfind = Sheetfind + 1`

Hello Excel gurus

As above, I have provided code which essentially opens up a document with a name specified from a cell in Excel, and finds the tab which has the same name as the value in cell P1 (As Sheetfind is 1, defined earlier in the code) and grabs data from it. No issues here, works fine.

My issue is, I get an error if that particular sheet doesn't exist, for example if the code is looking for '14 July 2018' and that sheet wasn't created by the searched person. I can't figure out a way of cycling through date ranges in column P until it hits a match.

I thought sheetfind +1 might work, as it would go from "p1" to "p2", but I can't figure out how to do this. P2 in this instance, would be the '13 July 2018'.

Any advice is massively appreciated - thanks in advance all.

While I generally advise against using this whenever possible, as it leads to bad coding habits of "when something doesn't work, simply supress it" , there are some cases (usually with opening/checking availability of Workbooks , Worksheets , etc when it can prove actually useful)


On Error Resume Next 'or you can refer to a block: instead of Next

suppresses errors all together, until it receives a callback

On Error GoTo 0

which switches VBA to default Error handling.
So wrapping your entire could inside it will suppress any potential errors.


But as I mentioned, people often tend to (over)rely on the Error suppression instead of actually doing proper coding themselves.

The right mentality and question you should be asking yourself is, how can I solve this problem without needing to rely on Error handling altogther?

In many cases (this one included), we could take the easy way out and suppress any potential errors, or we can actually do some proper coding and solve the issue the proper way!

Now I found it unclear, what exactly you're trying to do from your original code snippet. I presumed that you're trying to copy-paste range B2:D2 if found , but if not, just edit the code inside the if condition

Function inArray(ByVal what As String, ByVal in_array As Variant) As Boolean
    inArray = (UBound(Filter(in_array, what)) > -1)
    ' returns true if found, otherwise false
End Function


Private Sub check_sheets()

    Dim lr As Long ' last (active) row
    lr = Sheets("default").Cells(Rows.Count, "P").End(xlUp).Row

    Dim sheetnames() As String ' create array for our sheets
    ReDim sheetnames(1 To ThisWorkbook.Sheets.Count) ' size allocation

    Dim i As Long
    For i = 1 To ThisWorkbook.Sheets.Count
        sheetnames(i) = Sheets(i).Name ' store sheetname inside array
    Next i

    Dim cell As Range ' looping through column P
    For Each cell In Sheets("default").Range("P1:P" & lr)
        If (inArray(cell.Value2, sheetnames) = True) Then
            ' worksheet found, do something...
            Sheets("default").Range("B2:D2").Copy
            Sheets(cell.Value2).Range("B2").PasteSpecial xlPasteValues
        Else
            ' worksheet not found, maybe do something...?
            MsgBox ("Sheet " & cell.Value2 & " not found!")
        End If
    Next cell

End Sub

This answer also presumes that the column P with sheetnames is in a Worksheet called " default "


In general you can see my answer has a lot of variables, but that's what happens when the question is not clearly specified, unfortunately.
Either way, this answer should be more than sufficient with whatever you're trying to achieve :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM