Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用FileDialog打开工作簿并在Excel VBA中对其进行操作_Vba_Excel_Openfiledialog - Fatal编程技术网

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

使用FileDialog打开工作簿并在Excel VBA中对其进行操作,vba,excel,openfiledialog,Vba,Excel,Openfiledialog,我正在学习如何使用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", "*.xl

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

此代码打开文件对话框。如何打开选定的Excel文件而不重写以前打开的文件?

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

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

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)

谢谢你,弗兰克,我知道了。 这是工作代码

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

你所说的“不过度书写之前打开的内容”是什么意思?此代码仅保存所选文件的路径。无论如何,如果使用
CTRL+O
打开文件,则不会重写文件。请澄清您的问题。是的,这段代码只是保存路径,但我想打开所选文件。如果我再次运行宏,它应该在新工作簿中打开excel文件。它缺少显示文件对话框的说明:fd。show不要错过使用以下命令销毁“fd”变量:将fd=Nothing设置到函数的最后一行,并使用“wb”也