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

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

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文件而不覆盖以前打开的文件?

Thankyou 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 

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

要从用户获取文件path使用此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 

然后打开只读文件并将其分配给一个variables:

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