1
0

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.

【Excel VBA】開いているワークブックの名称をチェックする関数

Posted at

エクセルVBAで指定したWorkbookがあるか調べる2つの方法 をコピペして利用していたら「保護されたビュー」で引っかかったので。

TL;DR

VBA
'原型は、https://www.excelspeedup.com/getworkbook/ から
'同名のファイルが既に開かれていた場合に合致したWorkbook型を返す関数.
'1つも引っかからなければNothingを返す
Function getWorkbookByName(targetWorkbookName) As Workbook
  Dim TempWorkbook As Workbook
  For Each TempWorkbook In Workbooks
    If TempWorkbook.Name = targetWorkbookName Then
      Set getWorkbookByName = TempWorkbook
      Exit Function
    End If
  Next
  
  '上の処理(Workbooksから取得)だと「保護ビュー」のワークブックが引っかからない問題があるので、下記で解決する
  Dim TempWorkbook2 As Workbook
  Dim size As Long
  size = Application.ProtectedViewWindows.Count
  For i = 1 To size
    Set TempWorkbook2 = Application.ProtectedViewWindows(i).Workbook
    If TempWorkbook2.Name = targetWorkbookName Then
      Set getWorkbookByName = TempWorkbook2
      Exit Function
    End If
  Next
  
  Set getWorkbookByName = Nothing
End Function

雑な解説

Workbooks は保護されたビューを含まない。
従って Application.ProtectedViewWindows から引っ張ってきてforループで逐次する処理を追加している。

VBAに不慣れなので、より効率的な書き方があったらマサカリを投げて頂ければ幸いです。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?