从另一个工作簿向动态表添加条目

时间:2020-09-25 13:36:49

标签: excel vba

August 2020

Charges

嗨,大家好,我有一份2020年8月工作簿的条目列表(第一张图片。工作簿= 2020年8月,Sheet1),我想在代表我整个发票金额(第二个)的数据末尾添加到动态表格中图片,工作簿=费用,Sheet1。我想设置代码,以便当9月数字通过时可以将其添加到表格的末尾,等等。

我的代码在下面,(我们现在可以忽略日期列M!)

Sub Pullinfo()
'Pull information from the monthly data onto the charge loader file.
'1 - Set Variables
Dim lr As Long 'research doc sheet
Dim lastrow As Long 'IC Charge sheet
lr = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
lastrow = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row 'last row IC Charge

'2. Copy and paste

Workbooks("August2020").Activate
Sheets("Sheet1").Select
Range("B2:B" & lr).Copy
Workbooks("Charges.xls").Activate
Sheets("Sheet1").Select
Range("A14").pastespecial Paste:=xlPasteValues

Workbooks("August2020").Activate
Sheets("Sheet1").Select
Range("P2:P" & lr).Copy
Workbooks("Charges.xls").Activate
Sheets("Sheet1").Select
Range("J14").pastespecial Paste:=xlPasteValues

Workbooks("August2020").Activate
Sheets("Sheet1").Select
Range("R2:R" & lr).Copy
Workbooks("Charges.xls").Activate
Sheets("Sheet1").Select
Range("L14").pastespecial Paste:=xlPasteValuesAndNumberFormats

Workbooks("August2020").Activate
Sheets("Sheet1").Select
Range("S2:S" & lr).Copy
Workbooks("Charges.xls").Activate
Sheets("Sheet1").Select
Range("L14").pastespecial Paste:=xlPasteValuesAndNumberFormats
''

请注意,我知道我将这些值粘贴到数据的开头(第14行),但是我不确定如何将其粘贴到表的末尾并设置代码,以便为新价值。谢谢

1 个答案:

答案 0 :(得分:1)

以下内容可能会有所帮助:

Sub CopyMonthlyData()
    Dim wb_mth As Workbook, wb_charges As Workbook, mapFromColumn As Variant, mapToColumn As Variant
    Dim lastCell As Integer, i As Integer, nextCell As Integer
    
    Set wb_mth = Workbooks("September 2020")
    Set wb_charges = Workbooks("Charges")
    
    mapFromColumn = Array("A", "P", "Q")
    mapToColumn = Array("A", "J", "K")

        For i = 0 To UBound(mapFromColumn)
            
            With wb_mth.Worksheets(1)
            
                lastCell = .Range(mapFromColumn(i) & .Rows.Count).End(xlUp).Row
                .Range(mapFromColumn(i) & 1 & ":" & mapFromColumn(i) & lastCell).Copy
                
            End With

            With wb_charges.Worksheets(1)
            
                nextCell = .Range(mapToColumn(i) & .Rows.Count).End(xlUp).Row + 1
                .Range(mapToColumn(i) & nextCell).PasteSpecial
            
            End With
            
        Next i
    
End Sub

注释

  1. 首先设置对两个工作簿的引用。我认为两者都是开放的。
  2. 创建从每月工作簿到费用工作簿的列映射
  3. 遍历每个映射以复制和粘贴数据