用值填充列,直到最后一行

时间:2019-05-13 13:06:21

标签: excel vba

我的代码应从Excel文件TimeSheet复制数据。每个文件都包含带有人名的标题,并带有每日记录的块。代码循环了文件夹中的所有excel文件,并将记录追加到主文件。代码在这里已部分解决。但是现在我在用人名填写A列时遇到了问题。

代码应首先在NewSht的B列中填充任务,然后从提交的B7 OldSht中获取值,并将其复制到A列NewSht的第一个空单元格,并填充直到B列的最后一行。使用当前代码,我得到

  

“ Range类的自动填充方法失败”

错误。

Sub AllFiles()

Application.EnableCancelKey = xlDisabled

Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
Dim Masterwb  As Workbook
Dim sh As Worksheet
Dim NewSht As Worksheet
Dim OldSht As Worksheet
Dim FindRng As Range
Dim target As Range
Dim LastRow As Long

' set master workbook
Set Masterwb = Workbooks("result2.xlsm")

folderPath = "C:\Users\TimeSheets2019\inside" 'contains folder path

If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
Application.ScreenUpdating = False

Filename = Dir(folderPath & "*.xlsx*")
Do While Filename <> ""
    Set wb = Workbooks.Open(folderPath & Filename, ReadOnly:=True)
    Set NewSht = Masterwb.Worksheets("Tabelle1") ' added
    Set OldSht = wb.Worksheets("Manager Form") ' added

    ' get the first empty row in the new sheet
    Set FindRng = NewSht.Cells.Find(What:="*", Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
    Set target = NewSht.Cells(NewSht.Rows.Count, 2).End(xlUp).Offset(1, 0)
LastRow = NewSht.Range("B" & Rows.Count).End(xlUp).Row
    'copy taks list to column B            
    OldSht.Range("B7:B15, B17:B26").Copy
    NewSht.Cells(NewSht.Rows.Count, 2).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
' copy person name until last row in coulmn B
    OldSht.Range("B5").AutoFill Destination:=NewSht.Range("A2:A" & LastRow), Type:=xlFillDefault
    wb.Close False

Exit_Loop:
    Set wb = Nothing
    Filename = Dir
Loop
Application.ScreenUpdating = True

End Sub

TimeSheet to copy

Results in Master file

1 个答案:

答案 0 :(得分:2)

正如注释中已经指出的那样,Range.AutoFill仅在目标范围包括源范围时才有效。您无法从一张纸自动填充到另一张纸。

我认为您只需要在这里进行简单的值转移即可:

NewSht.Range("A2:A" & LastRow).Value = OldSht.Range("B5").Value