【问题标题】:Excel VBA Open a FolderExcel VBA 打开一个文件夹
【发布时间】:2025-12-17 08:55:01
【问题描述】:

使用 2010 Excel VBA - 我只是想通过子打开一个文件夹。我在这里做错了什么?

VBA

Sub openFolder()  
  Dim preFolder As String, theFolder As String, fullPath as String

    theFolder = Left(Range("T12").Value, 8)
    preFolder = Left(Range("T12").Value, 5) & "xxx"
    fullPath = "P:\Engineering\031 Electronic Job Folders\" & preFolder & "\" & theFolder

    Shell(theFolder, "P:\Engineering\031 Electronic Job Folders\" & preFolder, vbNormalFocus)

End Sub

【问题讨论】:

  • 文件夹打开后你想做什么?
  • Shell 只接受两个参数。如前所述,不清楚您在做什么
  • 我希望用户能够单击一个按钮并在屏幕上打开文件夹 - 没有别的。

标签: vba excel directory excel-2010


【解决方案1】:

如果你想打开一个windows文件资源管理器,你应该调用explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

等价语法

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

【讨论】:

  • @d-stroyer,你很接近。这条线看起来像shell "explorer.exe /e,z:\MyPath\To\Folder"
  • 如果路径中有空格,我认为您还需要将路径放在引号中。
  • 这可以简化为Shell("explorer.exe P:\Engineering", vbNormalFocus)。但是,对于空格,它们需要被双引号,两次,正如 Tim 提到的:Shell("explorer.exe ""P:\Engineering\031 Electronic Job Folders""", vbNormalFocus)
【解决方案2】:

我用它打开一个工作簿,然后将该工作簿的数据复制到模板中。

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'下面是将文件复制到工作簿中的新工作表中,并将这些值粘贴到工作表 1 中

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

【讨论】: