简体   繁体   English

VBA-在文件夹中打开文件并打印名称

[英]VBA - Open files in folder and print names

I want to open all of the files in a certain folder and have it print out the names of those files. 我想打开某个文件夹中的所有文件,并打印出这些文件的名称。

I have set up a code that opens the files but I cannot get it to print the name. 我已经设置了一个打开文件的代码,但是我无法获取它来打印名称。 I have a separate code that will print the name but will only open one file. 我有一个单独的代码,它将打印名称,但只会打开一个文件。 I'm failing at combining the two together correctly. 我无法将两者正确地结合在一起。 Any ideas? 有任何想法吗?

Code that opens all Excel files: 打开所有Excel文件的代码:

‘set path to progress folder
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
MyFolder = “C:\Users\trembos\Documents\TDS\progress"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Workbooks.Open fileName:=MyFolder & "\" & MyFile
    MyFile = Dir
Loop
End Sub

Code that prints one file name: 打印一个文件名的代码:

'set path to TDS_Working
Sub TDS()
    Workbooks.Open ("C:\Users\trembos\Documents\TDS\progress")
End Sub

'set up dim
Sub LoopThroughDirectory()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object

Dim i As Integer

'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the folder object
Set objFolder = objFSO.GetFolder("C:\Users\trembos\Documents\TDS\progress\")
i = 1
'loop through directory file and print names
For Each objFile In objFolder.Files
    'print file name
    Cells(i + 1, 1) = objFile.Name
Next objFile
End Sub

This should work smoothly : 这应该工作顺利:

   Sub LoopThroughDirectory()

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim MyFolder As String
    Dim Sht As Worksheet
    Dim i As Integer

    MyFolder = "C:\Users\trembos\Documents\TDS\progress\"

Set Sht = ActiveSheet

    'create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'get the folder object
    Set objFolder = objFSO.GetFolder(MyFolder)
    i = 1
    'loop through directory file and print names
    For Each objFile In objFolder.Files

        If LCase(Right(objFile.Name, 3)) <> "xls" And LCase(Left(Right(objFile.Name, 4), 3)) <> "xls" Then
        Else
            'print file name
            Sht.Cells(i + 1, 1) = objFile.Name
            i = i + 1
            Workbooks.Open Filename:=MyFolder & objFile.Name
        End If
    Next objFile

    End Sub
‘set path to progress folder
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
ActiveSheet.Unprotect ("password")
MyFolder = “C:\Users\trembos\Documents\TDS\progress"
MyFile = Dir(MyFolder & "\*.xlsx")
i=1
Do While MyFile <> ""
Workbooks.Open fileName:=MyFolder & "\" & MyFile
    MyFile = Dir
    Cells(i + 1, 1) =Myfile
    i=i+1
Loop
ActiveSheet.Protect ("password")
End Sub

Does this not work? 这行不通吗?

您只需要在循环内迭代i: i=i+1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM