如何使用循环在excel VBA中动态选择特定单元格?

时间:2018-12-13 17:32:13

标签: excel vba excel-vba loops

下面是我的代码

Sub Append()
    'Append data from other files
    Path = "E:\NPM PahseIII\"
    Filename = Dir(Path & "*.xlsx")
    If InStr(Filename, ".") > 0 Then
        Filenamenoext = Left(Filename, InStr(Filename, ".") - 1)
    End If
    MsgBox Filenamenoext
    Range("A3").Select
    Do While Filename <> ""
        ActiveCell.Value = Filenamenoext
    Loop
End Sub

我的问题是,由于我选择Range("A3").Select是硬编码的,所以我希望此选择在循环中动态完成,以便在循环的第一次迭代开始时应选择Range("A3").Select&在下一次迭代中进一步选择下一个单元格。 我怎样才能做到这一点? 已编辑 见下图 image

1 个答案:

答案 0 :(得分:2)

赞(未品尝):

Sub Append()

    Const FPath As String = "E:\NPM PahseIII\"
    Dim c As Range, Filename 

    'find the first empty cell in ColA
    Set c = activesheet.cells(rows.count, 1).end(xlup).offset(1, 0)

    Filename = Dir(FPath & "*.xlsx")
    Do While Filename <> ""
        c.Value = Split(Filename, ".")(0) 'note: problem if any of your file names have embedded periods...
        Set c = c.offset(1, 0)
        Filename = Dir()
    Loop

End Sub