简体   繁体   中英

Exit a For Each Loop with nested If Statement

I would like to exit the For Each Loop if ClientWork**** = "" and then also since we have a nested If statement in this loop that calls a function, I would like to avoid adding a sheet that has a blank name and no data. So this is what I have tried and also what happened as a result of my efforts:

I have a For Each Loop:

 For Each q In Range(ClientWork****) 
 Sheets("Schedules").Activate
  ClName = q.Value
  TabName = ClName

and a nested If statement that references a function called "SheetExists":

  If SheetExists(TabName) = False Then
    'Add a new worksheet
    Sheets.Add After:=Sheets(Sheets.Count)
    'Set newSheet variable to the new worksheet.
    Set NewSheet = ActiveSheet
    NewSheetName = ClName

I would like to exit the For each loop if "ClientWork****" = "" so to that end just above the Next q statement we have:

    If ClientWork**** = "" then Exit For

thinking that it would bypass the entire For Each loop.

I am hoping that this will work but first there is this problem:

SheetExists is a function and when SheetExists = False then it returns and adds a sheet and it does a whole lot more. So in the SheetExists function my thinking was to make sure it returned SheetExists = True. The function is as follows:

 Function SheetExists(sheetName As String)
   Dim Sheet As Worksheet
     For Each sheet in Sheets
       If sheet.Name = sheetName Then
          SheetExists = True
          Exit Function
       else
          SheetExists = False
        End If
       Next
     End Function

Okay, in the first section of the If statement I included an OR argument:

     If sheet.Name = sheetName OR sheetName = "" Then
       SheetExists = True
       Exit Function

In the hopes that a sheet with a blank name would not be added.

No joy ... it still adds a sheet, namely a sheet with a blank name and then this creates problems down the line when trying to format this sheet thinking there is data to format.

Any suggestions?

I'm not sure you can create a sheet without a name. Have you confirmed that the value is blank rather than say a space?

Additionally i would not add the functionality to the SheetExists function. That does one very explicit job: Does the sheet exist? Leave it as such.

I would add it into this statement. It will read more clearly then.

If SheetExists(TabName) = False And TabName <> "" Then

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