简体   繁体   English

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

[英]Open a workbook using FileDialog and manipulate it in Excel VBA

I am learning how to use Excel macros and I found this code: 我正在学习如何使用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

This code opens the FileDialog. 此代码将打开FileDialog。 How can I open the selected Excel file without over-writing the previously opened? 如何打开所选的Excel文件而不覆盖以前打开的Excel文件?

Thankyou Frank.i got the idea. 谢谢Frank.i有了这个主意。 Here is the working code. 这是工作代码。

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

Unless I misunderstand your question, you can just open a file read only. 除非我误解了您的问题,否则您只能打开一个只读文件。 Here is a simply example, without any checks. 这是一个简单的示例,没有进行任何检查。

To get the file path from the user use this function: 要从用户获取文件路径,请使用此功能:

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

Then just open the file read only and assign it to a variable: 然后,只需以只读方式打开文件并将其分配给变量即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM