시트가 있는지 테스트 또는 확인
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
기본적으로 원본 통합 문서의 모든 시트를 반복 한 다음 destsheet
대상 통합 문서에서 원본 통합 문서 의 현재 반복 된 시트와 동일한 이름을 가진 시트로 설정합니다.
해당 시트가 있는지 어떻게 테스트 할 수 있습니까? 다음과 같은 것 :
If wkbkdestination.Worksheets(ThisWorkSheet.Name) Then
일부 사람들은 오류 처리의 "부적절한"사용으로 인해이 접근 방식을 싫어하지만 VBA에서 허용되는 것으로 간주됩니다. 대체 접근 방식은 일치하는 항목을 찾을 때까지 모든 시트를 반복하는 것입니다.
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
특별히 워크 시트에만 관심이있는 경우 간단한 Evaluate 호출을 사용할 수 있습니다.
Function WorksheetExists(sName As String) As Boolean
WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function
이를 수행하기 위해 오류 처리가 필요하지 않습니다. 모든 워크 시트를 반복하고 지정된 이름이 있는지 확인하기 만하면됩니다.
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
컬렉션의 구성원을 확인하는 것이 일반적인 문제이므로 다음은 Tim의 답변을 추상화 한 버전입니다.
함수 Contains (objCollection As Object, strName as String) As Boolean 개체로 Dim o 오류시 다음 재개 o = objCollection (strName) 설정 포함 = (Err.Number = 0) Err. Clear 끝 기능
이 기능 (오브젝트와 같은 모음으로 사용될 수있는 Shapes
, Range
, Names
, Workbooks
, 등).
시트의 존재를 확인하려면 If Contains(Sheets, "SheetName") ...
수정 됨 : 오류 처리 없음 :
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
누구나 VBA를 피하고 워크 시트가 순수하게 셀 수식 내에 있는지 테스트하려는 경우 ISREF
및 INDIRECT
함수를 사용할 수 있습니다.
=ISREF(INDIRECT("SheetName!A1"))
이 반환됩니다 TRUE
통합 문서라는 시트가 포함되어있는 경우 SheetName
와 FALSE
그렇지.
나는 이것을 썼다.
Function sheetExist(sSheet As String) As Boolean
On Error Resume Next
sheetExist = (ActiveWorkbook.Sheets(sSheet).Index > 0)
End Function
내 솔루션은 Tims와 비슷하지만 워크 시트가 아닌 시트의 경우에도 작동합니다.
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
.
테스트를 함수에 넣으면 다시 사용할 수 있고 코드 가독성이 향상됩니다.
"On Error Resume Next"는 코드의 다른 부분과 충돌 할 수 있으므로 사용하지 마십시오.
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
컴팩트 wsExists
기능 ( 오류 처리에 의존 하지 않음 !)
여기에 워크 시트가 존재하는지 여부를 결정하는 오류 처리에 의존하지 않는 짧은 및 간단한 함수이다 ( 그리고 제대로 직장에 선언 어떤 상황!)
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
사용 예 :
다음 예제에서는라는 새 워크 시트 myNewSheet
가 아직없는 경우 추가 합니다.
If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"
추가 정보:
- MSDN :
For Each
…Next
성명서 (VBA) - MSDN :
Exit
Statement (VBA) - MSDN : Comparison Operators (VBA)
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
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.
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
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
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
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
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
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.
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.
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
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
참고URL : https://stackoverflow.com/questions/6688131/test-or-check-if-sheet-exists
'programing tip' 카테고리의 다른 글
Swift에서 SQLite 데이터베이스에 액세스 (0) | 2020.08.18 |
---|---|
JavaScript IF 문에서 OR 조건을 사용하는 방법은 무엇입니까? (0) | 2020.08.17 |
Perl과 PHP의 차이점 (0) | 2020.08.17 |
'ng build'후 angular-cli에서 dist-folder 경로를 변경하는 방법 (0) | 2020.08.17 |
UNIX 쉘 스크립트에서 10 진수를 16 진수로 변환 (0) | 2020.08.17 |