Excel VBA FSO.GetFolder(folderPath)在2007年工作,但不2010

所以我对VBA来说很新。

下面的代码在2007年工作正常,列出所有的PDF files在一个特定的文件夹。 然而,这段代码似乎并没有工作,当我在Excel 2010中尝试它(它会引发错误Set fold = fso.GetFolder(folderPath)

任何想法我做错了什么?

我有脚本运行时检查。 我的代码如下:

 Sub List_files() Dim fso As FileSystemObject Dim fold As Folder Dim f As File Dim folderPath As String Dim i As Integer folderPath = "S:\Academic Affairs\Academic Operations Reporting\CV's" Set fso = New FileSystemObject Set fold = fso.GetFolder(folderPath) i = 2 For Each f In fold.Files If LCase(Right(f.Name, 3)) = "pdf" Then Range("A" & i).Value = f.Name i = i + 1 End If Next End Sub 

我想你需要一个“\”的folderPathvariables…所以它是

folderPath =“S:\ Academic Affairs \ Academic Operations Reporting \ CV's \”

如果这不能解决它,发布你得到的错误。

这里是我用来列出文件的一个过程:

 Function GetFileList(pDirPath As String) As Variant On Error GoTo GetFileList_err ' Local constants / variables Const cProcName = "GetFileList" Dim objFSO As Object Dim objFolder As Object Dim objFile As Object Dim c As Double ' upper bound for file name array Dim i As Double ' iterator for file name array Dim vFileList() As String ' array for file names Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.GetFolder(pDirPath) c = objFolder.Files.Count i = 0 ReDim vFileList(1 To c) ' set bounds on file array now we know count 'Loop through the Files collection For Each objFile In objFolder.Files 'Debug.Print objFile.Name i = i + 1 vFileList(i) = objFile.Name Next 'Clean up! Set objFolder = Nothing Set objFile = Nothing Set objFSO = Nothing GetFileList = vFileList GetFileList_exit: Exit Function GetFileList_err: Debug.Print "Error in ", cProcName, " Err no: ", Err.Number, vbCrLf, "Err Description: ", Err.Description Resume Next End Function Sub PrintFileList(pDirPath As String, _ Optional pPrintToSheet = False, _ Optional pStartCellAddr = "$A$1", _ Optional pCheckCondition = False, _ Optional pFileNameContains) On Error GoTo PrintFileList_err ' Local constants / variables Const cProcName = "PrintFileList" Dim vFileList() As String ' array for file names Dim i As Integer ' iterator for file name array Dim j As Integer ' match counter Dim c As String vFileList = GetFileList(pDirPath) c = pStartCellAddr j = 0 For i = LBound(vFileList) To UBound(vFileList) If pPrintToSheet Then If pCheckCondition Then ' if pFileNameContains not in filename go to next iteration of loop If InStr(1, vFileList(i), pFileNameContains, vbTextCompare) = 0 Then GoTo EndLoop End If End If Range(c).Offset(j, 0).Value = vFileList(i) j = j + 1 End If 'Debug.Print vFileList(i) i = i + 1 EndLoop: Next PrintFileList_exit: Exit Sub PrintFileList_err: Debug.Print "Error in ", cProcName, vbCrLf, "Err no: ", Err.Number, _ vbCrLf, "Err Description: ", Err.Description Resume Next End Sub 

该function仅供内部使用,您可以调用该程序。 这是一个示例调用(在这种情况下,使用userprofile windows环境variables作为path而不是硬编码path):

 call PrintFileList(environ("userprofile"), True, "$A$1", True, ".pdf")