Excel if does not exist

Dim wkbkdestination As Workbook
Dim destsheet As Worksheet

For Each ThisWorkSheet In wkbkorigin.Worksheets 
    'this throws subscript out of range if there is not a sheet in the destination 
    'workbook that has the same name as the current sheet in the origin workbook.
    Set destsheet = wkbkdestination.Worksheets(ThisWorkSheet.Name) 
Next

Basically I loop through all sheets in the origin workbook then set destsheet in the destination workbook to the sheet with the same name as the currently iterated one in the origin workbook.

How can I test if that sheet exists? Something like:

If wkbkdestination.Worksheets(ThisWorkSheet.Name) Then 

BigBen's user avatar

BigBen

43.9k6 gold badges27 silver badges40 bronze badges

asked Jul 14, 2011 at 3:23

yse's user avatar

1

Some folk dislike this approach because of an «inappropriate» use of error handling, but I think it’s considered acceptable in VBA… An alternative approach is to loop though all the sheets until you find a match.

Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
    Dim sht As Worksheet

    If wb Is Nothing Then Set wb = ThisWorkbook
    On Error Resume Next
    Set sht = wb.Sheets(shtName)
    On Error GoTo 0
    WorksheetExists = Not sht Is Nothing
End Function

darcyy's user avatar

darcyy

5,2165 gold badges27 silver badges41 bronze badges

answered Jul 14, 2011 at 4:27

Tim Williams's user avatar

Tim WilliamsTim Williams

150k8 gold badges96 silver badges124 bronze badges

14

If you are specifically interested in worksheets only, you can use a simple Evaluate call:

Function WorksheetExists(sName As String) As Boolean
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function

answered Feb 12, 2015 at 9:25

Rory's user avatar

RoryRory

32.4k5 gold badges31 silver badges34 bronze badges

10

You don’t need error handling in order to accomplish this. All you have to do is iterate over all of the Worksheets and check if the specified name exists:

Dim exists As Boolean

For i = 1 To Worksheets.Count
    If Worksheets(i).Name = "MySheet" Then
        exists = True
    End If
Next i

If Not exists Then
    Worksheets.Add.Name = "MySheet"
End If

ke1v3y's user avatar

answered Mar 27, 2013 at 20:21

fbonetti's user avatar

fbonettifbonetti

6,5823 gold badges33 silver badges32 bronze badges

1

I wrote this one:

Function sheetExist(sSheet As String) As Boolean
On Error Resume Next
sheetExist = (ActiveWorkbook.Sheets(sSheet).Index > 0)
End Function

answered Apr 16, 2018 at 19:24

AOBR's user avatar

AOBRAOBR

2792 silver badges4 bronze badges

3

As checking for members of a collection is a general problem, here is an abstracted version of @Tim’s answer:

Function Contains(objCollection As Object, strName as String) As Boolean
    Dim o as Object
    On Error Resume Next
    set o = objCollection(strName)
    Contains = (Err.Number = 0)
    Err.Clear
 End Function

This function can be used with any collection like object (Shapes, Range, Names, Workbooks, etc.).

To check for the existence of a sheet, use If Contains(Sheets, "SheetName") ...

shA.t's user avatar

shA.t

16.4k5 gold badges53 silver badges111 bronze badges

answered Jan 24, 2013 at 20:11

Peter Albert's user avatar

Peter AlbertPeter Albert

16.8k4 gold badges66 silver badges88 bronze badges

2

Corrected:
Without error-handling:

Function CheckIfSheetExists(SheetName As String) As Boolean
      CheckIfSheetExists = False
      For Each WS In Worksheets
        If SheetName = WS.name Then
          CheckIfSheetExists = True
          Exit Function
        End If
      Next WS
End Function

answered Feb 17, 2015 at 14:07

Shai Alon's user avatar

Shai AlonShai Alon

95013 silver badges20 bronze badges

0

In case anyone wants to avoid VBA and test if a worksheet exists purely within a cell formula, it is possible using the ISREF and INDIRECT functions:

=ISREF(INDIRECT("SheetName!A1"))

This will return TRUE if the workbook contains a sheet called SheetName and FALSE otherwise.

answered Jan 7, 2016 at 6:33

VirtualMichael's user avatar

Compact wsExists function (without reliance on Error Handling!)

Here’s a short & simple function that doesn’t rely on error handling to determine whether a worksheet exists (and is properly declared to work in any situation!)

Function wsExists(wsName As String) As Boolean
    Dim ws: For Each ws In Sheets
    wsExists = (wsName = ws.Name): If wsExists Then Exit Function
    Next ws
End Function

Example Usage:

The following example adds a new worksheet named myNewSheet, if it doesn’t already exist:

If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"

More Information:

  • MSDN : For EachNext Statement (VBA)
  • MSDN : Exit Statement (VBA)
  • MSDN : Comparison Operators (VBA)

answered May 11, 2018 at 16:56

ashleedawg's user avatar

ashleedawgashleedawg

20k8 gold badges73 silver badges104 bronze badges

My solution looks much like Tims but also works in case of non-worksheet sheets — charts

Public Function SheetExists(strSheetName As String, Optional wbWorkbook As Workbook) As Boolean
    If wbWorkbook Is Nothing Then Set wbWorkbook = ActiveWorkbook 'or ThisWorkbook - whichever appropriate
    Dim obj As Object
    On Error GoTo HandleError
    Set obj = wbWorkbook.Sheets(strSheetName)
    SheetExists = True
    Exit Function
HandleError:
    SheetExists = False
End Function

.

answered Aug 3, 2014 at 15:43

uildriks's user avatar

uildriksuildriks

511 silver badge1 bronze badge

Many years late, but I just needed to do this and didn’t like any of the solutions posted… So I made one up, all thanks to the magic of (SpongeBob rainbow hands gesture) «Evaluate()»!

Evaluate("IsError(" & vSheetName & "!1:1)")

Returns TRUE if Sheet does NOT exist; FALSE if sheet DOES exist.
You can substitute whatever range you like for «1:1», but I advise against using a single cell, cuz if it contains an error (eg, #N/A), it will return True.

answered Aug 1, 2016 at 16:37

X37V's user avatar

1

Short and clean:

Function IsSheet(n$) As Boolean
    IsSheet = Not IsError(Evaluate("'" & n & "'!a1"))
End Function

Roy Latham's user avatar

answered Apr 3, 2020 at 4:13

Excel Hero's user avatar

Excel HeroExcel Hero

14.1k4 gold badges31 silver badges39 bronze badges

0

Put the test in a function and you will be able to reuse it and you have better code readability.

Do NOT use the «On Error Resume Next» since it may conflict with other part of your code.

Sub DoesTheSheetExists()
    If SheetExist("SheetName") Then
        Debug.Print "The Sheet Exists"
    Else
        Debug.Print "The Sheet Does NOT Exists"
    End If
End Sub

Function SheetExist(strSheetName As String) As Boolean
    Dim i As Integer

    For i = 1 To Worksheets.Count
        If Worksheets(i).Name = strSheetName Then
            SheetExist = True
            Exit Function
        End If
    Next i
End Function

answered Jan 9, 2014 at 9:26

Martin Carlsson's user avatar

Martin CarlssonMartin Carlsson

4512 gold badges6 silver badges17 bronze badges

Public Function WorkSheetExists(ByVal strName As String) As Boolean
   On Error Resume Next
   WorkSheetExists = Not Worksheets(strName) Is Nothing
End Function

sub test_sheet()

 If Not WorkSheetExists("SheetName") Then
 MsgBox "Not available"
Else MsgBox "Available"
End If

End Sub

answered Aug 5, 2013 at 10:56

M1NT's user avatar

M1NTM1NT

3861 gold badge4 silver badges13 bronze badges

Why not just use a small loop to determine whether the named worksheet exists? Say if you were looking for a Worksheet named «Sheet1» in the currently opened workbook.

Dim wb as Workbook
Dim ws as Worksheet

Set wb = ActiveWorkbook

For Each ws in wb.Worksheets

    if ws.Name = "Sheet1" then
        'Do something here
    End if

Next

answered Jan 16, 2015 at 7:55

ScottMcC's user avatar

ScottMcCScottMcC

3,9441 gold badge27 silver badges35 bronze badges

    For Each Sheet In Worksheets
    If UCase(Sheet.Name) = "TEMP" Then
    'Your Code when the match is True
        Application.DisplayAlerts = False
        Sheet.Delete
        Application.DisplayAlerts = True
    '-----------------------------------
    End If
Next Sheet

answered Mar 28, 2017 at 12:24

Shrikant's user avatar

ShrikantShrikant

5234 silver badges15 bronze badges

If you are a fan of WorksheetFunction. or you work from a non-English country with a non-English Excel this is a good solution, that works:

WorksheetFunction.IsErr(Evaluate("'" & wsName & "'!A1"))

Or in a function like this:

Function WorksheetExists(sName As String) As Boolean
    WorksheetExists = Not WorksheetFunction.IsErr(Evaluate("'" & sName & "'!A1"))
End Function

answered May 23, 2017 at 9:25

Vityata's user avatar

VityataVityata

42.4k8 gold badges55 silver badges98 bronze badges

Change «Data» to whatever sheet name you’re testing for…

On Error Resume Next 

Set DataSheet = Sheets("Data")

If DataSheet Is Nothing Then

     Sheets.Add(after:=ActiveSheet).Name = "Data"
     ''or whatever alternate code you want to execute''
End If

On Error GoTo 0

Dan Lowe's user avatar

Dan Lowe

49.9k19 gold badges123 silver badges111 bronze badges

answered Jul 10, 2017 at 16:54

gth826a's user avatar

gth826agth826a

1011 silver badge4 bronze badges

Without any doubt that the above function can work, I just ended up with the following code which works pretty well:

Sub Sheet_exist ()
On Error Resume Next
If Sheets("" & Range("Sheet_Name") & "") Is Nothing Then
    MsgBox "doesnt exist"
Else
    MsgBox "exist"
End if
End sub

Note: Sheets_Name is where I ask the user to input the name, so this might not be the same for you.

Cody Gray's user avatar

Cody Gray

237k50 gold badges488 silver badges570 bronze badges

answered Jun 28, 2016 at 2:24

MAx Segura's user avatar

I did another thing: delete a sheet only if it’s exists — not to get an error if it doesn’t:

Excel.DisplayAlerts = False 
Dim WS
For Each WS In Excel.Worksheets
    If WS.name = "Sheet2" Then
        Excel.sheets("Sheet2").Delete
        Exit For
    End If
Next
Excel.DisplayAlerts = True

answered Feb 17, 2015 at 15:22

Shai Alon's user avatar

Shai AlonShai Alon

95013 silver badges20 bronze badges

I use this function to check and return a new sheet name if needed. WSname is the desired worksheet name and WBCur is the workbook you would like to check in. I use this because there is no need for error handling and can call it whenever i am creating a new worksheet.

Public Function CheckNewWorksheetName(WSName As String, WBCur As Workbook) 'Will return New Name if needed
    Dim NewWSNum As Long, A As Integer, B As Integer, WorksheetFound As Boolean
    NewWSNum = 1
    WorksheetFound = False
    For A = 1 To WBCur.Worksheets.Count
        If WBCur.Worksheets(A).Name = WSName Then
            A = WBCur.Worksheets.Count
            WorksheetFound = True
        End If
    Next A
    
    If WorksheetFound = False Then
        CheckNewWorksheetName = WSName
    Else
        Do While WorksheetFound = True
            WorksheetFound = False
            For B = 1 To WBCur.Worksheets.Count
                If WBCur.Worksheets(B).Name = WSName & "_" & NewWSNum Then
                    B = WBCur.Worksheets.Count
                    WorksheetFound = True
                    NewWSNum = NewWSNum + 1
                End If
            Next B
        Loop
        CheckNewWorksheetName = WSName & "_" & NewWSNum
    End If
End Function

answered Jul 14, 2021 at 19:51

Alex Johnson's user avatar

I came up with an easy way to do it, but I didn’t create a new sub for it. Instead, I just «ran a check» within the sub I was working on. Assuming the sheet name we’re looking for is «Sheet_Exist» and we just want to activate it if found:

Dim SheetCounter As Integer

SheetCounter = 1

Do Until Sheets(SheetCounter).Name = "Sheet_Exist" Or SheetCounter = Sheets.Count + 1
 SheetCounter = SheetCounter +1
Loop
If SheetCounter < Sheets.Count + 1 Then
 Sheets("Sheet_Exist").Activate
Else
 MsgBox("Worksheet ""Sheet_Exist"" was NOT found")
End If

I also added a pop-up for when the sheet doesn’t exist.

answered Jun 14, 2018 at 15:13

imjordy23's user avatar

I know it is an old post, but here is another simple solution that is fast.

Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean

On Error Resume Next
worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
Err.Clear: On Error GoTo 0

End Function

answered Apr 4, 2019 at 15:39

Guest's user avatar

GuestGuest

4302 silver badges4 bronze badges

I actually had a simple way to check if the sheet exists and then execute some instruction:

In my case I wanted to delete the sheet and then recreated the same sheet with the same name but the code was interrupted if the program was not able to delete the sheet as it was already deleted

Sub Foo ()

    Application.DisplayAlerts = False

    On Error GoTo instructions
    Sheets("NAME OF THE SHEET").Delete

    instructions:

    Sheets.Add After:=Sheets(Sheets.Count)
    ActiveSheet.Name = "NAME OF THE SHEET"

End Sub

Cody Gray's user avatar

Cody Gray

237k50 gold badges488 silver badges570 bronze badges

answered Mar 7, 2014 at 14:47

chenaou's user avatar

1

  • Редакция Кодкампа

17 авг. 2022 г.
читать 2 мин


Вы можете использовать следующую формулу в Excel для выполнения какой-либо задачи, если ячейка не пуста:

=IF( A1 <> "" , Value_If_Not_Empty, Value_If_Empty)

Эта конкретная формула проверяет, пуста ли ячейка A1 .

Если он не пустой, то возвращается Value_If_Not_Empty .

Если он пуст, возвращается значение Value_If_Empty .

В следующем примере показано, как использовать эту формулу на практике.

Пример: используйте формулу «Если не пусто» в Excel

Предположим, у нас есть следующий набор данных в Excel, который содержит информацию о различных баскетбольных командах:

Мы можем использовать следующую формулу, чтобы вернуть значение «Команда существует», если ячейка в столбце A не пуста.

В противном случае мы вернем значение «Не существует»:

=IF( A2 <> "" , "Team Exists", "Does Not Exist")

На следующем снимке экрана показано, как использовать эту формулу на практике:

Если имя команды не пусто в столбце А, возвращается «Команда существует».

В противном случае возвращается «Не существует».

Если бы мы хотели, мы могли бы также возвращать числовые значения вместо символьных значений.

Например, мы могли бы использовать следующую формулу, чтобы вернуть значение столбца очков, разделенное на два, если ячейка в столбце A не пуста.

В противном случае мы вернем пустое значение:

=IF( A2 <> "" , B2 / 2 , "" )

На следующем снимке экрана показано, как использовать эту формулу на практике:

Формула Excel для «если не пусто»

Если название команды не пусто в столбце A, то мы возвращаем значение в столбце очков, умноженное на два.

В противном случае мы возвращаем пустое значение.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные задачи в Google Таблицах:

Как отфильтровать ячейки, содержащие текст, в Google Sheets
Как извлечь подстроку в Google Sheets
Как извлечь числа из строки в Google Sheets

Return to Excel Formulas List

Download Example Workbook

Download the example workbook

This tutorial demonstrates how to use the COUNTIF function to determine if a value exists in a range.

Test if Value Exists in a Range main Function

COUNTIF Value Exists in a Range

To test if a value exists in a range, we can use the COUNTIF Function:

=COUNTIF(Range, Criteria)>0

The COUNTIF function counts the number of times a condition is met. We can use the COUNTIF function to count the number of times a value appears in a range. If COUNTIF returns greater than 0, that means that value exists.

=COUNTIF($E$3:$E$9,B3)

PIC 01

By attaching “>0” to the end of the COUNTIF Function, we test if the function returns >0. If so, the formula returns TRUE (the value exists).

=COUNTIF($E$3:$E$9,B3)>0

PIC 02

You can see above that the formula results in a TRUE statement for the name “Patrick Mitchell. On the other hand, the name “Georgia Smith” and “Patrick Svensen” does not exist in the range $B$2:$B$31.

You can wrap this formula around an IF Function to output a specific result. For example, if we want to add a “Does not exist” text for names that are not in the list, we can use the following formula:

=IF(COUNTIF($B$2:$B$31, Name)>0, “Exists”, “Does Not Exist”)

count if value exists in range if function

COUNTIF Value Exists in a Range Google Sheets

We use the same formula structure in Google Sheets:

=IF(COUNTIF(Range, Criteria)>0, “Exists”, “Does Not Exist”)

count if value exists in range google sheets

Example

=ISREF(INDIRECT(“‘”&B3&”‘!A1”))

Generic Formula

=ISREF(INDIRECT(“‘”&SheetName&”‘!A1”))

SheetName – This is the text which you want to test if it exists as a worksheet in the current workbook.

What It Does

This formula will test if a sheet exists in the current workbook and return TRUE if the sheet exists or FALSE if it does not exist.

How It Works

“‘”&SheetName&”‘!A1” will create a text reference to cell A1 in a sheet with the name SheetName. In our example “‘”&”My Sheet”&”‘!A1” creates the text string ‘My Sheet’!A1 which references cell A1 in sheet ‘My Sheet’ if it exists. INDIRECT will then return a reference specified by this text string. ISREF will then return TRUE if this is a valid reference and will return FALSE if it’s not a valid reference because the sheet doesn’t exist.

About the Author

John MacDougall

John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.

Subscribe

Subscribe for awesome Microsoft Excel videos 😃

John MacDougall

I’m John, and my goal is to help you Excel!

You’ll find a ton of awesome tips, tricks, tutorials, and templates here to help you save time and effort in your work.

Get the Latest Microsoft Excel Tips

Follow Us

Follow us to stay up to date with the latest in Microsoft Excel!

Subscribe for awesome Microsoft Excel videos 😃

User18000601 posted

Guys i am trying to generate an Excel file. I am able to generate one but I want to do a check if the file does exist or not. If exist , overwrite it , otherwise create a new one and save. I try with my code below, it doesnt work out. Any one could help
me with this? Thank you very much. 

public void btnTest_Click(object sender, EventArgs e) 
        {
            
            Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
            string file = "TestingAccounts.xls";
            Workbook wb = new Workbook();
            Worksheet ws = new Worksheet();
            
            object misValue = System.Reflection.Missing.Value;
            try
            {
                wb = xla.Workbooks.Open(file, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
                ws = (Worksheet)wb.Worksheets.get_Item(1);
                xla.Workbooks.Open(file);

                Range last = ws.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
                Range range = ws.get_Range("A1", last);

                int lastUsedRow = last.Row + 1;
                ws.Cells[lastUsedRow, 1] = "abc";

                xla.DisplayAlerts = false;
                wb.SaveAs(file, XlFileFormat.xlAddIn, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                wb.Close(true, misValue, misValue);

                xla.Quit();

                releaseObject(ws);
                releaseObject(wb);
                releaseObject(xla);
            }
            catch
            {
                MessageBox.Show("The excel file is not exist. Click ok to create new one");
                wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
                ws = (Worksheet)xla.ActiveSheet;

                xla.DisplayAlerts = false;
                wb.SaveAs(file, XlFileFormat.xlAddIn, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                
                wb.Close(true, misValue, misValue);

                xla.Quit();

                releaseObject(ws);
                releaseObject(wb);
                releaseObject(xla);

            }
            //xla.Visible = true;
            
        }

Понравилась статья? Поделить с друзьями:
  • Excel if copy format
  • Excel if concatenate string
  • Excel if column is not empty
  • Excel if color macro
  • Excel if check for text