excel - 在添加数组之前检查文件扩展名是否为 .xlsx

标签 excel vba

我为我创建了一个循环来获取特定文件夹中的文件,但我想知道如何确保将添加到 myArray 中的文件名仅包含 .xlsx 或 .xls?

Function listFiles(ByVal get_Path As String)

Dim myArray As Variant
Dim i As Integer
Dim counter As Integer
Dim xFile As Object
Dim FileServ As Object
Dim the_Folder As Object
Dim the_Files As Object

Set FileServ = CreateObject("Scripting.FileSystemObject")
Set the_Folder = FileServ.GetFolder(get_Path)
Set the_Files = the_Folder.Files

    'Check if folder is empty
    If the_Files.Count = 0 Then
        Exit Function
    End If

    'Declare the size of Array based on the number of Files inside the folder
    ReDim myArray(1 To the_Files.Count)

    'Loop through each file and assign each filename in Array
    i = 1
    For Each xFile In the_Files
        myArray(i) = xFile.Name
        i = i + 1
    Next


    listFiles = myArray

End Function

最佳答案

你可以这样做:

i = 0
For Each xFile In the_Files
    If xFile.Name Like "*.xls" or xFile.Name Like "*.xlsx" Then
        i = i + 1
        myArray(i) = xFile.Name
    End If
Next

Redim Preserve myArray(1 to i)

关于excel - 在添加数组之前检查文件扩展名是否为 .xlsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56334085/

相关文章:

使用动态文件名保存到 SharePoint 的 VBA 宏

vba - 为什么会弹出 "Delete Method of Range class failed"错误?

excel - 打开工作簿时自动显示 IDE

vba - 自动填充到列中的最后一行

excel - 使用 Excel Vba 浏览网站

excel - 为什么Excel VBA中 'Row'更改为 'row'

multithreading - MS Access 中的多线程,异步处理

Excel 加载项有时无法加载

vba - 在崩溃时初始化图表对象VBA

excel - 确定是否按下了取消按钮,其中 InputBox 变量声明为 Double