gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:21:31 25 4
gpt4 key购买 nike

我想打开某个文件夹中的所有文件并让它打印出这些文件的名称。

我已经设置了打开文件的代码,但无法让它打印名称。我有一个单独的代码,可以打印名称,但只能打开一个文件。我无法正确地将两者结合在一起。有什么想法吗?

打开所有 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

打印一个文件名的代码:

'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

最佳答案

这应该可以顺利进行:

   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

关于VBA - 打开文件夹中的文件并打印名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30531757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com