Excel for Windows および Excel for the Mac でプログラムによってファイルを選択する
**概要:**Microsoft Excel for Microsoft Window と Microsoft Excel for the Mac の GetOpenFilename メソッドについて、および Mac 用のこのメソッドの制限を解消する方法について説明します。
適用対象: Excel 2010 | Office 2010 | SharePoint Server 2010 | VBA
公開: 2011 年 12 月
提供元: Ron de Bruin、Excel MVP | Frank Rice、Microsoft Corporation
目次
GetOpenFileName メソッドの概要
GetOpenFilename メソッドの詳細
Windows と Mac の実装の違い
Windows で GetOpenFilename メソッドを使用する
Mac の Excel 2011 で GetOpenFilename メソッドを使用するための対処方法
Windows または Mac で適切なマクロを実行する
まとめ
その他の技術情報
GetOpenFileName メソッドの概要
Microsoft Excel for Mac 2011 を使用すると、すべてのデータとリストを分析、編成、および管理できます。その情報は、オンラインで簡単に保存、編集、および共有することができます。一般的に、開発者はコードを記述し、プログラムによってユーザーが 1 つ以上のファイルをダイアログ ボックスで選択できるようにします。これを行うには、Application.GetOpenFilename メソッドを使用します。このメソッドは、標準の [開く] ダイアログ ボックスを表示し、ファイルを実際に開かずに、ユーザーからファイル名を取得します。通常、ファイル名は変数に返され、後からマクロで使用されます。
GetOpenFilename メソッドは、Excel for Microsoft Windows および Excel for the Macintosh (Mac) が実行されているコンピューターで使用します。ただし、各オペレーティング システムでのメソッドの実装方法には違いがあります。この記事では、その違いと、Mac でメソッドを使用するときの対処方法について説明します。
GetOpenFilename メソッドの詳細
前に説明したように、GetOpenFilename メソッドは、標準の [開く] ダイアログ ボックスを表示し、指定されたファイル名を、ユーザーによって入力されたフィルターが適用されたリストから取得します。次の表では、メソッドのパラメーターについて説明します。
名前 |
必須またはオプション |
データ型 |
説明 |
---|---|---|---|
FileFilter |
オプション |
バリアント |
ファイル フィルター基準を指定する文字列。 |
FilterIndex |
オプション |
バリアント |
既定のファイル フィルター基準のインデックス番号を、1 から FileFilter で指定されたフィルター番号の範囲内で指定します。この引数を省略した場合、または存在するフィルター番号よりも引数の方が大きい場合は、最初のファイル フィルターが使用されます。 |
Title |
オプション |
バリアント |
ダイアログ ボックスのタイトルを指定します。この引数を省略した場合、タイトルは [開く] になります。 |
ButtonText |
オプション |
バリアント |
Mac でのみ使用されます。 |
MultiSelect |
オプション |
バリアント |
True に設定すると、複数のファイル名を選択できます。False の場合は、1 つのファイル名しか選択できません。既定値は False です。 |
FileFilter 引数に渡されるデータは、ファイル フィルター文字列と MS-DOS ワイルドカード ファイル フィルターのペアで構成され、各部分および各ペアがコンマで区切られています。たとえば、Text Files (*.txt),*.txt は、テキスト ファイルのフィルターを指定します。
Windows と Mac の実装の違い
GetOpenFilename メソッドの実装方法には、Microsoft Windows と Mac の間にいくつか違いがあります。上記の表で示すように、Mac で使用できるのは ButtonText パラメーターのみです。FileFilter パラメーターと MultiSelect パラメーターは Mac では使用できません。これらのパラメーターがないので、GetOpenFileName は、Mac ではあまり便利とは言えません。ただし、この記事で後述する Apple Script による対処方法により、同じ機能を利用することはできます。
GetOpenFilename メソッドを呼び出したときに開くフォルダーを設定するときの動作は、Mac と Windows では異なります。Windows では、ChDrive および ChDir を使用してこのフォルダーを設定します。これらの引数は、Mac では動作しません。これに対処するには、Apple Script でコード行を使用し、このフォルダーを設定します。
注意
Microsoft Excel 2002 for Windows 以降を使用している場合は、Application.FileDialog メソッドを使用することもできます。さらに、GetOpenFileName メソッドは、Microsoft Excel 97 および Microsoft Excel 2000 でも動作します。
以下のセクションでは、Windows が実行されているコンピューターで GetOpenFilename メソッドを使用する方法について説明します。
Windows で GetOpenFilename メソッドを使用する
次に示す例では、Windows が実行されているコンピューターで GetOpenFilename メソッドを使用しています。コード例では、次のタスクを実行します。
現在のディレクトリを保存し、そのディレクトリを、MyPath 変数で設定したフォルダーに変更します。
参照ダイアログ ボックスと、MyPath 変数によって指定されたフォルダーをアクティブ フォルダーとして開き、このフォルダー内の .xls ファイルのみを表示します。
MultiSelect 引数が True に設定されているので、1 つ以上のファイルを選択します。
選択した各ファイルを 1 つずつ開き、ファイル名が示されたメッセージ ボックスを表示します。MsgBox 行は、必要に応じて、独自のコードに置き換えることができます。
ファイルを保存しないで閉じます。SaveChanges 引数を True に設定すると、ファイルを保存できます。
GetOpenFilename メソッドを Excel for Windows に追加するには
標準のモジュールを、ブック内の Microsoft Visual Basic for Applications (VBA) プロジェクトに追加します。Alt キーを押しながら F11 キーを押して Visual Basic Editor を開き、[挿入]、[モジュール] の順にクリックします。
次のマクロをモジュールに貼り付けるか入力します。
Sub Select_File_Or_Files_Windows() Dim SaveDriveDir As String Dim MyPath As String Dim Fname As Variant Dim N As Long Dim FnameInLoop As String Dim mybook As Workbook ' Save the current directory. SaveDriveDir = CurDir ' Set the path to the folder that you want to open. MyPath = Application.DefaultFilePath ' You can also use a fixed path. 'MyPath = "C:\Users\Ron de Bruin\Test" ' Change drive/directory to MyPath. ChDrive MyPath ChDir MyPath ' Open GetOpenFilename with the file filters. Fname = Application.GetOpenFilename( _ FileFilter:="Excel 97-2003 Files (*.xls), *.xls", _ Title:="Select a file or files", _ MultiSelect:=True) ' Perform some action with the files you selected. If IsArray(Fname) Then With Application .ScreenUpdating = False .EnableEvents = False End With For N = LBound(Fname) To UBound(Fname) ' Get only the file name and test to see if it is open. FnameInLoop = Right(Fname(N), Len(Fname(N)) - InStrRev(Fname(N), Application.PathSeparator, , 1)) If bIsBookOpen(FnameInLoop) = False Then Set mybook = Nothing On Error Resume Next Set mybook = Workbooks.Open(Fname(N)) On Error GoTo 0 If Not mybook Is Nothing Then MsgBox "You opened this file : " & Fname(N) & vbNewLine & _ "And after you press OK, it will be closed" & vbNewLine & _ "without saving. You can replace this line with your own code." mybook.Close SaveChanges:=False End If Else MsgBox "We skipped this file : " & Fname(N) & " because it is already open." End If Next N With Application .ScreenUpdating = True .EnableEvents = True End With End If ' Change drive/directory back to SaveDriveDir. ChDrive SaveDriveDir ChDir SaveDriveDir End Sub Function bIsBookOpen(ByRef szBookName As String) As Boolean ' Contributed by Rob Bovey On Error Resume Next bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing) End Function
さらにフィルターを追加するには、マクロ内で次のコードを使用して, .xls ファイルおよび .csv ファイルでフィルター処理を実行します。
Fname = Application.GetOpenFilename( _ FileFilter:="XLS Files (*.xls),*.xls,CSV Files (*.csv),*.csv", _ Title:="Select a file or files", _ MultiSelect:=True)
Alt キーを押しながら Q キーを押して、Visual Basic Editor を閉じます。
Alt キーを押しながら F8 キーを押して、マクロ ダイアログ ボックスを開き、マクロを実行します。
Mac の Excel 2011 で GetOpenFilename メソッドを使用するための対処方法
前のセクションで説明したように、Excel 2011 での GetOpenFileName メソッドの使用には制限が伴うので、最適なオプションとは言えません。ただし、VBA コードと Apple Script を組み合わせて使用すれば、同じ操作を実行できます。これを行うには、次の説明に従って、Apple Script 文字列を作成し、その文字列を VBA MacScript 関数と実行します。コード例では、次のタスクを実行します。
参照ダイアログ ボックスと、MyPath 値をアクティブ フォルダーとして開き、このフォルダー内の .xls ファイルのみを表示します。
Apple Script で複数選択のオプションが True に設定されているので、1 つ以上のファイルを選択します。
選択した各ファイルを 1 つずつ開き、ファイル名が示されたメッセージ ボックスを表示します。MsgBox 行を独自のコードに置き換えて、ファイルごとに必要な操作を行うことができます。
ファイルを保存しないで閉じます。SaveChanges 引数を True に設定すると、ファイルを保存できます。
Excel for the Mac で 1 つ以上のファイルを選択するには
Visual Basic Editor を開くには、[ツール]、[マクロ]、[Visual Basic Editor] の順にクリックします。
標準のモジュールを挿入するには、[挿入]、[モジュール] の順にクリックします。
次のマクロおよび関数をモジュールに貼り付けるか入力します。
Sub Select_File_Or_Files_Mac() Dim MyPath As String Dim MyScript As String Dim MyFiles As String Dim MySplit As Variant Dim N As Long Dim Fname As String Dim mybook As Workbook On Error Resume Next MyPath = MacScript("return (path to documents folder) as String") 'Or use MyPath = "Macintosh HD:Users:Ron:Desktop:TestFolder:" ' In the following statement, change true to false in the line "multiple ' selections allowed true" if you do not want to be able to select more ' than one file. Additionally, if you want to filter for multiple files, change ' {""com.microsoft.Excel.xls""} to ' {""com.microsoft.excel.xls"",""public.comma-separated-values-text""} ' if you want to filter on xls and csv files, for example. MyScript = _ "set applescript's text item delimiters to "","" " & vbNewLine & _ "set theFiles to (choose file of type " & _ " {""com.microsoft.Excel.xls""} " & _ "with prompt ""Please select a file or files"" default location alias """ & _ MyPath & """ multiple selections allowed true) as string" & vbNewLine & _ "set applescript's text item delimiters to """" " & vbNewLine & _ "return theFiles" MyFiles = MacScript(MyScript) On Error GoTo 0 If MyFiles <> "" Then With Application .ScreenUpdating = False .EnableEvents = False End With MySplit = Split(MyFiles, ",") For N = LBound(MySplit) To UBound(MySplit) ' Get the file name only and test to see if it is open. Fname = Right(MySplit(N), Len(MySplit(N)) - InStrRev(MySplit(N), Application.PathSeparator, , 1)) If bIsBookOpen(Fname) = False Then Set mybook = Nothing On Error Resume Next Set mybook = Workbooks.Open(MySplit(N)) On Error GoTo 0 If Not mybook Is Nothing Then MsgBox "You open this file : " & MySplit(N) & vbNewLine & _ "And after you press OK it will be closed" & vbNewLine & _ "without saving, replace this line with your own code." mybook.Close SaveChanges:=False End If Else MsgBox "We skipped this file : " & MySplit(N) & " because it Is already open." End If Next N With Application .ScreenUpdating = True .EnableEvents = True End With End If End Sub Function bIsBookOpen(ByRef szBookName As String) As Boolean ' Contributed by Rob Bovey On Error Resume Next bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing) End Function
次に、Cmd キーを押しながら Q キーを押すか、[Excel]、[閉じる] の順にクリックし、Visual Basic Editor を閉じます。
[ツール]、[マクロ]、[マクロ] の順にクリックし、マクロ ダイアログ ボックスを開き、マクロを実行します。
注意
また、[開発者] タブをリボンに追加して Excel 2011 のマクロを実行することもできます。Excel を起動して、メニュー バーの [Excel] をクリックし、メニューの [基本設定] をクリックします。[Excel 環境設定] ウィンドウが開いたら、[リボン] をクリックします。[リボン] ページが開いたら、[カスタマイズ] リストを下にスクロールし、[開発者] を選択します。[OK] をクリックして、変更内容を保存します。
このコードは、xls ファイルでのみフィルター処理を実行します。他には次のオプションがあります。
xlsx: org.openxmlformats.spreadsheetml.sheet
xlsm: org.openxmlformats.spreadsheetml.sheet.macroenabled
xlsb: com.microsoft.Excel.sheet.binary.macroenabled
xls: com.microsoft.Excel.xls
csv: public.comma-separated-values-text
docx: org.openxmlformats.wordprocessingml.document
docm: org.openxmlformats.wordprocessingml.document.macroenabled
doc: com.microsoft.word.doc
pptx: org.openxmlformats.presentationml.presentation
pptm: org.openxmlformats.presentationml.presentation.macroenabled
ppt: com.microsoft.powerpoint.ppt
Windows または Mac で適切なマクロを実行する
Windows ユーザーと Mac ユーザーの両方がいる場合、各オペレーティング システムでファイルの検索をプログラムで実行するには、前に示した両方のマクロを Excel プロジェクトに追加し、次のマクロを使用して、特定のオペレーティング システムをテストしたうえで、適切なマクロを実行します。
Sub WINorMAC()
' Test for the operating system.
If Not Application.OperatingSystem Like "*Mac*" Then
' Is Windows.
Call Select_File_Or_Files_Windows
Else
' Is a Mac and will test if running Excel 2011 or higher.
If Val(Application.Version) > 14 Then
Call Select_File_Or_Files_Mac
End If
End If
End Sub
Sub WINorMAC_2()
' Test the conditional compiler constants.
#If Win32 Or Win64 Then
' Is Windows.
Call Select_File_Or_Files_Windows
#Else
' Is a Mac and will test if running Excel 2011 or higher.
If Val(Application.Version) > 14 Then
Call Select_File_Or_Files_Mac
End If
#End If
End Sub
まとめ
この記事では、GetOpenFilename メソッドについて説明し、このメソッドを Windows バージョンと Mac バージョンの Excel で実装する方法の違いについて説明しました。また、Mac におけるメソッドの制限を解消する方法も確認しました。こうした情報を把握することで、どの方法が、使用しているアプリケーションに適しているかについて適切な判断を下すことができます。
その他の技術情報
この記事に記載されているトピックの詳細については、次の追加情報を参照してください。