Excel VBA - 删除文件对话框

Posted

技术标签:

【中文标题】Excel VBA - 删除文件对话框【英文标题】:Excel VBA - remove FileDialog 【发布时间】:2016-02-17 08:57:19 【问题描述】:

我正在使用以下代码列出文件夹中的文件。

代码很好用,但是我不需要用户选择文件夹,文件夹每次都是一样的。

我可以删除文件对话框吗?

With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Choose the folder"
    .Show
End With

为了每次都列出同一文件夹中的文件,我需要用什么替换它?

Sub FolderNames()

Application.ScreenUpdating = False
Dim xPath As String
Dim xWs As Worksheet
Dim fso As Object, j As Long, folder1 As Object
With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Choose the folder"
    .Show
End With
On Error Resume Next
xPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"
Application.Workbooks.Add
Set xWs = Application.ActiveSheet
xWs.Cells(1, 1).Value = xPath
xWs.Cells(2, 1).Resize(1, 5).Value = Array("Path", "Dir", "Name", "Date Created", "Date Last Modified")
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder1 = fso.getFolder(xPath)
getSubFolder folder1
xWs.Cells(2, 1).Resize(1, 5).Interior.Color = 65535
xWs.Cells(2, 1).Resize(1, 5).EntireColumn.AutoFit
Application.ScreenUpdating = True
End Sub
Sub getSubFolder(ByRef prntfld As Object)
Dim SubFolder As Object
Dim subfld As Object
Dim xRow As Long
For Each SubFolder In prntfld.SubFolders
    xRow = Range("A1").End(xlDown).Row + 1
    Cells(xRow, 1).Resize(1, 5).Value = Array(SubFolder.Path, Left(SubFolder.Path, InStrRev(SubFolder.Path, "\")), SubFolder.Name, SubFolder.DateCreated, SubFolder.DateLastModified)
Next SubFolder
For Each subfld In prntfld.SubFolders
    getSubFolder subfld
Next subfld
End Sub

【问题讨论】:

如果您的文件夹路径是静态的,您只需将 xPath 设置为您的文件夹路径并删除 FileDialog 相关行。 【参考方案1】:

对不起,我认为我很愚蠢 - 我已经回答了我自己的问题。 不确定这是否是最好的方法,但这似乎可以正常工作。

我替换以下内容;

With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Choose the folder"
    .Show
End With
On Error Resume Next
xPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"

有;

Dim toplvl As String
toplvl = "W:\ISO 9001\INTEGRATED_PLANNING"
xPath = toplvl & "\"

【讨论】:

是的,就是这样做的。或者删除这 3 行新行,删除 Dim xPath,将 Const TOPLVL As String = "W:\ISO 9001\INTEGRATED_PLANNING\" 放在模块的最顶部,然后使用 TOPLVL 而不是 xPath

以上是关于Excel VBA - 删除文件对话框的主要内容,如果未能解决你的问题,请参考以下文章

excel vba做出一个打开文件对话框:

VBA 打开一个 Excel 文件 - 对话框更改

Excel VBA中的文件保存对话框

excel文件打开时 vba满足条件弹窗提醒?

VB弹出打开对话框,选择文件excel文件

VBA 文件对话框 .FileName 从文件名末尾删除 .1