使用FileDialog应用程序的问题

时间:2013-03-19 12:25:11

标签: excel vba excel-vba

我有一些代码,我正在努力改进但有一些问题。

目前代码:

    Sub TestListFilesInFolder()
'Workbooks.Add ' create a new workbook for the file list
' add headers

Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker) ' Tried using a FileDialog Application  but had no luck

With Range("A1")
    .Formula = "Folder contents:"
    .Font.Bold = True
    .Font.Size = 12
End With
Range("A3").Formula = "Old File Path:"
Range("B3").Formula = "File Type:"
Range("C3").Formula = "File Name:"
Range("D3").Formula = "New File Path:"
Range("A3:H3").Font.Bold = True
ListFilesInFolder "L:\Pictures\A B C\B526 GROUP", True
' ListFilesInFolder fd, True ' I tried replacing the above line with this line but get an error

' list all files included subfolders
 End Sub

第5行和第6行是我添加的部分,我试图打开一个文件对话框,用户可以在其中选择要处理的代码的文件夹。

另外,底部起始ListFilesInFolder附近的注释掉的行是我试图插入的替换它上面的行。

下一段代码的开头是:

   Sub ListFilesInFolder(SourceFolderName As String, IncludeSubfolders As Boolean)

因此它使用第一个子目录中定义的文件夹的文件夹和子文件夹。

对此有任何帮助将不胜感激。

此致

萨姆

2 个答案:

答案 0 :(得分:0)

您将fd作为第一个参数传递给ListFilesInFolder子。此子订单接受String作为第一个参数, a FileDialog

这是一些示例代码,在执行时将打开文件对话框并让用户选择一个文件夹。选择后,它会将文件夹的路径打印到B2。如果未选择任何文件夹(例如,对话框已关闭或取消),则B2将包含文字No item selected

我认为你应该创建一个新的工作簿并使用这个宏。设置一个断点并浏览它,看看它实际上在做什么。然后你可以改变它以使它适合你的特定需求。

Public Sub SelectExportDestinationPath()
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = strPath
        If .Show <> -1 Then
            sItem = "No item selected"
        Else
            sItem = .SelectedItems(1)
        End If
    End With

    'if trailing slash is not found, add it
    If Len(sItem) > 0 And InStr(Len(sItem), sItem, Application.PathSeparator, vbCompareText) = 0 Then
        sItem = sItem & Application.PathSeparator
    End If

    Sheet1.Cells(2, 2).Value = sItem

    Set fldr = Nothing
End Sub

答案 1 :(得分:-1)

确保您选择了适当的参考:

  

按Alt + F11打开VB编辑器。在该窗口中,选择菜单项工具 - &gt;引用...,然后查看 Microsoft Office XXX对象库的列表    Access 2003的11.0,Access 2002的10.0; 9.0 for Access 2000,8.0 for Access 97 - 选择正确的。
  在该引用旁边的框中打勾,然后关闭对话框。

或者,使用实际值,而不是mso值

msoFileDialogOpen=1
msoFileDialogSaveAs=2
msoFileDialogFilePicker=3
msoFileDialogFolderPicker=4