gpt4 book ai didi

excel - 将文件夹名称存储到数组中并按字母顺序排序 VBA

转载 作者:行者123 更新时间:2023-12-04 22:24:05 27 4
gpt4 key购买 nike

我有以下代码,旨在将每个文件名拉到特定路径中并将其放入数组中。出于某种原因,尽管文件资源管理器中的文件是按字母顺序排序的,但代码会将它们拉乱。我的方法是先将文件名存储到数组中,然后再对数组进行排序。有没有更好的方法来解决这个问题?

此外,由于某种原因,带有 Debug.Print arr1(i) 的行仅将空白打印到即时窗口。请指教。

Dim arr1(1000) As String, item As Variant
Dim x As Long, y As Long, k As Integer
Dim TempTxt1 As String
Dim TempTxt2 As String
Dim FolderPath As String, path As String, count As Integer
Dim size As Integer, i As Integer

Set oFSO = CreateObject("Scripting.FileSystemObject")

Set oFolder = oFSO.GetFolder("X:\test\testfolder")

For Each oFile In oFolder.Files

arr1(i) = Left(oFile.Name, Application.WorksheetFunction.Find(".", oFile.Name) - 1)

i = i + 1

Debug.Print arr1(i)

Next oFile


'Alphabetize Sheet Names in Array List
For x = LBound(arr1) To UBound(arr1)
For y = x To UBound(arr1)
If UCase(arr1(y)) < UCase(arr1(x)) Then
TempTxt1 = arr1(x)
TempTxt2 = arr1(y)
arr1(x) = TempTxt2
arr1(y) = TempTxt1
End If
Next y
Next x

在此处输入代码

最佳答案

所以根据我的评论;我认为您可能会受益于使用 ArrayList及其能力 Sort .尝试:

Sub Test()

Dim oFSO As Object, oFolder As Object, arr As Object

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("X:\test\testfolder")
Set arr = CreateObject("System.Collections.ArrayList")

For Each oFile In oFolder.Files
arr.Add oFSO.GetBaseName(oFile)
Next oFile

arr.Sort

End Sub

既然您一个接一个地提取名称,我们不妨在 ArrayList 中这样做。 . .Sort然后方法将按升序对列表进行排序。

关于excel - 将文件夹名称存储到数组中并按字母顺序排序 VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59721602/

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