【问题标题】:Open a workbook using FileDialog and manipulate it in Excel VBA使用 FileDialog 打开工作簿并在 Excel VBA 中对其进行操作
【发布时间】:2014-09-28 23:20:52
【问题描述】:

我正在学习如何使用 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

此代码打开 FileDialog。如何在不覆盖之前打开的情况下打开选定的 Excel 文件?

【问题讨论】:

  • “不覆盖之前打开的”是什么意思?此代码仅保存所选文件的路径。无论如何,如果您使用CTRL + O 打开文件,则不会覆盖文件。请澄清您的问题。
  • 是的,这段代码只是保存路径,但我想打开选定的文件。如果我再次运行宏,它应该在新工作簿中打开 excel 文件。

标签: vba excel openfiledialog


【解决方案1】:

谢谢弗兰克。我明白了。 这是工作代码。

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

【讨论】:

    【解决方案2】:

    除非我误解了您的问题,否则您可以只读方式打开文件。 这是一个简单的例子,没有任何检查。

    要从用户那里获取文件路径,请使用这个函数:

    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
    

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

    dim wb as workbook
    set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
    

    【讨论】:

    • 缺少显示 FileDialog 的指令:fd.Show
    • 不要错过使用以下方法破坏“fd”变量:将 fd = Nothing 设置到函数的最后一行,以及“wb”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2014-12-01
    相关资源
    最近更新 更多