VBA填充现有值直到最后一行

时间:2019-10-14 14:33:24

标签: excel vba

我已经有一个工作宏,该宏将5行转换为列,并将它们附加在最后一列之后。

问题是我需要一个长格式,所以基本上我想用相同的数据自动填充,直到数据结束(基本上是最后一行)。我有600个文件,所有这些文件的行数都不同。

Sub LoopFiles()
    Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.xls*")
        Do While xFileName <> ""
            With Workbooks.Open(xFdItem & xFileName)
                'your code here
                Range("A2:B6").Select
                Selection.Copy
                Range("I10").Select
                Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
                    False, Transpose:=True
                Rows("1:8").Select
                Application.CutCopyMode = False
                Selection.Delete Shift:=xlUp
                With Sheets("Calculated Saccades")
                    .Range("I3").AutoFill .Range("I4:I" & .Cells(.Rows.Count, "A").End(xlUp).Row)
                End With
                ActiveWorkbook.Save
                ActiveWorkbook.Close
            End With
            xFileName = Dir
        Loop
    End If
End Sub

With Sheets返回错误。有任何想法吗?非常感谢你!

1 个答案:

答案 0 :(得分:1)

您已经在With...End With块中(With Workbooks.Open(xFdItem & xFileName)-如果您在“文件打开”对话框中选择多个,则这会循环浏览工作簿);您不能嵌套这些。

您可以简单地替换

    With Sheets("Calculated Saccades")
  .Range("I3").AutoFill .Range("I4:I" & .Cells(.Rows.Count, "A").End(xlUp).Row)
    End With

具有:

    Sheets("Calculated Saccades").Range("I3").AutoFill
    Sheets("Calculated Saccades").Range("I4:I" & .Cells(.Rows.Count, "A").End(xlUp).Row)

您还应该阅读How to avoid using Select in Excel VBA