1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

選択範囲のセルにあるシート追加するマクロ

Posted at

ソースコード

Option Explicit

Function checkExistSheet(sheetName As String)
    Dim workSheet As workSheet
    Dim existFlag As Boolean
    
    For Each workSheet In worksheets
        If workSheet.Name = sheetName Then existFlag = True
    Next workSheet
    
    
'    If flag = True Then
'        MsgBox "[合計]シートがあります", vbInformation
'    Else
'        MsgBox "[合計]シートはありません", vbInformation
'    End If

    checkExistSheet = existFlag
    
End Function

Sub addSheet(sheetName As String)

    If sheetName <> "" Then
        worksheets.Add(After:=worksheets(worksheets.count)) _
             .Name = sheetName
    End If
         
End Sub

' 引数で指定した範囲の最終行を取得
Function getLastRowRejectSplace(targetRange As Range) As Long
    getLastRowRejectSplace = Cells(Rows.count, targetRange.Column).End(xlUp).Row
End Function

Sub main()
    
    Dim selectionRange As Range
    Dim selectionCell As Range
    Dim lastRow As Long
    
    lastRow = getLastRowRejectSplace(Selection)
    
    For Each selectionCell In Selection
    
       If checkExistSheet(selectionCell.Value) = False Then
           Call addSheet(selectionCell.Value)
       End If

       If selectionCell.Row = lastRow Then
            Exit For
       End If
       
    Next selectionCell

End Sub
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?