Sprawdź lub sprawdź, czy arkusz istnieje
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
Zasadniczo przechodzę przez wszystkie arkusze skoroszytu origin, a następnie ustawiam destsheet
w skoroszycie docelowym na arkusz o tej samej nazwie, co obecnie iteracyjny w skoroszycie origin.
Jak mogę sprawdzić, czy ten arkusz istnieje? Coś w stylu:
If wkbkdestination.Worksheets(ThisWorkSheet.Name) Then
22 answers
Niektórzy ludzie nie lubią tego podejścia z powodu "niewłaściwego" użycia obsługi błędów, ale myślę, że jest to akceptowalne w VBA... Alternatywnym podejściem jest zapętlenie wszystkich arkuszy, dopóki nie znajdziesz dopasowania.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-12 08:46:32
Jeśli interesują Cię tylko arkusze robocze, możesz użyć prostego wywołania oceny:
Function WorksheetExists(sName As String) As Boolean
WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-12 09:25:59
Nie potrzebujesz obsługi błędów, aby to osiągnąć. Wszystko, co musisz zrobić, to iterację wszystkich arkuszy i sprawdzić, czy podana nazwa istnieje:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-27 20:21:55
Ponieważ sprawdzanie członków kolekcji jest ogólnym problemem, oto abstrakcyjna Wersja odpowiedzi Tima:
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
Ta funkcja może być używana z dowolnym zbiorem podobnym do obiektu (Shapes
, Range
, Names
, Workbooks
, itd.).
Aby sprawdzić istnienie arkusza, użyj If Contains(Sheets, "SheetName") ...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-29 07:06:16
Poprawiono: Bez obsługi błędów:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 16:03:01
W przypadku, gdy ktoś chce uniknąć VBA i sprawdzić, czy arkusz istnieje wyłącznie w formule komórki, możliwe jest użycie funkcji ISREF
i INDIRECT
:
=ISREF(INDIRECT("SheetName!A1"))
Zwróci TRUE
jeśli skoroszyt zawiera arkusz o nazwie SheetName
i FALSE
w przeciwnym razie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-07 06:33:32
Napisałem ten:
Function sheetExist(sSheet As String) As Boolean
On Error Resume Next
sheetExist = (ActiveWorkbook.Sheets(sSheet).Index > 0)
End Function
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-16 19:24:47
Moje rozwiązanie wygląda podobnie jak Tims, ale działa również w przypadku arkuszy bez arkuszy-Wykresów
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
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-03 15:43:43
Wiele lat później, ale po prostu musiałem to zrobić i nie spodobało mi się żadne z zamieszczonych rozwiązań... Więc wymyśliłem jeden, wszystko dzięki magii (gest tęczowych rąk SpongeBob) " Oceń ()"!
Evaluate("IsError(" & vSheetName & "!1:1)")
Zwraca TRUE, jeśli arkusz nie istnieje; FALSE, jeśli arkusz istnieje. Możesz zastąpić dowolny zakres "1: 1", ale odradzam używanie pojedynczej komórki, bo jeśli zawiera błąd (np. #N/A), zwróci True.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-01 16:37:47
Zwarta wsExists
Funkcja (bez polegania na obsłudze błędów!)
Oto krótka i prosta funkcja, która nie polega na obsłudze błędów w celu określenia, czy istnieje arkusz roboczy (i jest prawidłowo zadeklarowana do pracy w dowolnej sytuacji!)
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
Przykładowe Użycie:
Poniższy przykład dodaje nowy arkusz o nazwie myNewSheet
, Jeśli jeszcze nie istnieje:
If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"
Więcej Informacje:
- MSDN :
For Each
...Next
oświadczenie (VBA) - MSDN :
Exit
oświadczenie (VBA) - MSDN : operatory porównawcze (VBA)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-11 16:56:56
Umieść test w funkcji, a będziesz mógł go ponownie użyć i będziesz miał lepszą czytelność kodu.
Nie używaj "w przypadku błędu Wznów następny", ponieważ może to być sprzeczne z inną częścią kodu.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-09 09:26:05
Dlaczego po prostu nie użyć małej pętli, aby określić, czy nazwany arkusz istnieje? Powiedz, jeśli szukasz arkusza o nazwie "Arkusz1" w aktualnie otwartym skoroszycie.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-17 14:38:48
Jeśli jesteś fanem WorksheetFunction.
lub pracujesz z nie-angielskiego kraju z nie-angielskim Excel jest to dobre rozwiązanie, które działa:
WorksheetFunction.IsErr(Evaluate("'" & wsName & "'!A1"))
Lub w funkcji takiej jak Ta:
Function WorksheetExists(sName As String) As Boolean
WorksheetExists = Not WorksheetFunction.IsErr(Evaluate("'" & sName & "'!A1"))
End Function
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 09:31:26
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-05 10:56:52
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-28 12:24:50
Zmień "dane" na dowolną nazwę arkusza, dla którego testujesz...
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-10 17:19:35
Bez wątpienia powyższa funkcja może działać, właśnie skończyłem z następującym kodem, który działa całkiem dobrze:
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
Uwaga: Sheets_Name
to miejsce, w którym proszę użytkownika o podanie nazwy, więc może to nie być to samo dla Ciebie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-04 20:32:59
Zrobiłem jeszcze jedną rzecz: Usuń arkusz tylko wtedy, gdy istnieje-nie ma błędu, jeśli nie:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-17 15:22:04
Wymyśliłem łatwy sposób, aby to zrobić, ale nie stworzyłem dla niego nowego suba. Zamiast tego po prostu "sprawdziłem" łódź podwodną, nad którą pracowałem. Zakładając, że szukana nazwa arkusza to "Sheet_Exist" i chcemy ją aktywować, jeśli zostanie znaleziona:
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
Dodałem również wyskakujące okienko, gdy arkusz nie istnieje.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-14 15:21:16
Wiem, że to stary post, ale tutaj jest inne proste rozwiązanie, które jest szybkie.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-04 15:39:43
Krótkie i czyste:
Function IsSheet(n$) As Boolean
IsSheet = Not IsError(Evaluate(n & "!a1"))
End Function
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-03 04:13:26
Miałem prosty sposób, aby sprawdzić, czy arkusz istnieje, a następnie wykonać jakąś instrukcję:
W moim przypadku chciałem usunąć arkusz, a następnie odtworzyć ten sam arkusz o tej samej nazwie, ale kod został przerwany, jeśli program nie był w stanie usunąć arkusza, ponieważ został już usunięty
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-04 20:33:24