[PowerPoint VBA] How to Open an Excel File Selection Dialog from a UserForm

目次

Background

When building tools in PowerPoint VBA, there is often a need to “open a dialog to select an Excel file using a UserForm.”

Instead of asking users to type a file path manually, allowing them to select it via a file dialog is more reliable and convenient. In this article, I implemented a mechanism where clicking a button opens a dialog to select an Excel file, and the result is displayed in a text box.

Specifications

  • Use a UserForm in PowerPoint.
  • Clicking CommandButton1 opens the file selection dialog.
  • Restrict selection to Excel files (.xls, .xlsx, .xlsm).
  • Automatically input the selected file path into TextBox1.

UserForm Configuration

  • CommandButton1: A button to execute the file selection.
  • TextBox1: A text box to display the full path of the selected file.

Implementation Code (PowerPoint VBA)

Paste the following code into the code area of your UserForm.

' Call file selection process when button is clicked
Private Sub CommandButton1_Click()
    Call SelectFile(Me.TextBox1)
End Sub

' Show file dialog and set the result to the TextBox
Private Sub SelectFile(textbox As MSForms.TextBox)
    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        .Title = "Please select an Excel file."
        .Filters.Clear
        .Filters.Add "Excel Files", "*.xls; *.xlsx; *.xlsm", 1
        
        ' If the user clicks "Open" (.Show returns -1)
        If .Show = -1 Then
            textbox.Text = .SelectedItems(1)
        End If
    End With
End Sub

Code Explanation

  • Application.FileDialog(msoFileDialogFilePicker): This allows you to use the standard file selection dialog even within PowerPoint.
  • .Filters.Add: This filters the view to show only Excel files.
  • .Show = -1: This indicates that the user clicked the “Open” button. (If the user clicks Cancel, the code does nothing).

Important Notes

  • Ensure that the text box on your UserForm is a standard UserForm control (MSForms.TextBox).
  • This code is designed for PowerPoint VBA but utilizes standard Office dialog functionality.

Summary

  • You can call a file selection dialog from a UserForm in PowerPoint VBA.
  • Combining a CommandButton and a TextBox provides a user-friendly interface.
  • This prevents typos in file paths and leads to smoother automation.

I hope this helps anyone looking to perform file operations using PowerPoint VBA.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次