使用FileDialog打开工作簿并在Excel VBA中对其进行操作

use*_*866 13 excel vba openfiledialog excel-vba

我正在学习如何使用Excel宏,我发现这个代码:

Dim fd As Office.FileDialog

Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd

    .AllowMultiSelect = False
    .Title = "Please select the file to kill his non colored cells"
    .Filters.Add "Excel", "*.xls"
    .Filters.Add "All", "*.*"

    If .Show = True Then
        txtFileName = .SelectedItems(1)
    End If

End With
Run Code Online (Sandbox Code Playgroud)

此代码打开FileDialog.如何在不重写先前打开的情况下打开所选的Excel文件?

use*_*866 24

谢谢Frank.i明白了.这是工作代码.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub
Run Code Online (Sandbox Code Playgroud)


小智 7

除非我误解了你的问题,否则你只需打开一个只读的文件.这是一个简单的例子,没有任何检查.

要从用户获取文件路径,请使用以下函数:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function
Run Code Online (Sandbox Code Playgroud)

然后只打开文件只读并将其分配给变量:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
Run Code Online (Sandbox Code Playgroud)

  • 它缺少显示FileDialog:fd.Show的指令 (5认同)