2013-03-19 56 views
0

我有一些代码,我试图改善,但有一些问题。问题使用FileDialog应用程序

代码当前:

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) 

所以它使用在第一子定义文件夹的文件和子文件夹。

任何帮助,将不胜感激。

问候,

山姆

回答

1

你传递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 
+0

嗨,谢谢你的回复。这工作完美。谢谢 – SCGB 2013-03-19 15:52:31

+0

没问题 - 很高兴帮助。与您的项目的其余部分祝你好运。 – Sam 2013-03-19 16:04:50

-1

确保你有适当的参考选择的是:

按Alt + F11打开VB编辑器。在该窗口中,选择菜单项Tools - > References ...,然后在列表中查找列表Microsoft Office XXX对象库
Access 2003的10.0,Access 2002的10.0; Access 2000的9.0,Access 97的8.0 - 选择正确的一个。
勾选该参考旁边的复选框,然后关闭对话框。

,或者使用的实际值,而不是MSO值

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