0

得到下面的代码,但不是将第一个值放在单元格 A1 中,而是始终从 A3 开始。如何纠正这个?

Sub list_files()
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object

    Range("A1", Columns("A").End(xlDown)).Clear
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder("C:\files\")
    ActiveSheet.Cells(1, 1).Select
    For Each objFile In objFolder.Files
    ActiveSheet.Cells(ActiveSheet.UsedRange.Rows.Count + 1, 1).Value = objFile.Name
    Next
    Set objFolder = Nothing
    Set objFile = Nothing
    Set objFSO = Nothing
End Sub
4

1 回答 1

1

不要这样使用UsedRange。相反,只需增加一个变量,如下所示

Sub list_files()
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim rowNumber as long

    rowNumber = 1

    Range("A1", Columns("A").End(xlDown)).Clear
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder("C:\files\")

    For Each objFile In objFolder.Files

        ActiveSheet.Cells(rowNumber, 1).Value = objFile.Name
        rowNumber = rowNumber + 1

    Next
    Set objFolder = Nothing
    Set objFile = Nothing
    Set objFSO = Nothing
End Sub
于 2013-11-04T08:28:12.973 回答