Excel VBA - 向右添加列并填充文本

时间:2017-07-26 10:48:21

标签: excel-vba tablecolumn vba excel

我想编辑现有代码(下面),在2个工作簿之间复制和粘贴表格,以执行以下操作:

  1. 在“vDB”右侧添加新列(在末尾),这是wbTarget表格的副本
  2. 使用文本“TOTAL”
  3. 填充整个列
  4. 然后将其粘贴到另一个名为“sht1”

    的工作簿中
    Dim vDB As Variant
    Dim sht1 As Worksheet
    Dim wbTarget As Workbook 
    
    'if sheet name is "TOTAL" then...
    If "TOTAL" = Sheet.Name Then
    
        'copy a given range from the target workbook
        vDB = wbTarget.Sheets(Sheet.Name).Range("b3:i102")
    
        'paste that range under existing data in the master workbook
        sht1.Range("a" & Rows.Count).End(xlUp)(2).Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
    
    End If
    
  5. 我失败的尝试:

        Dim vDB As Variant
        Dim sht1 As Worksheet
        Dim wbTarget As Workbook 
    
        If "TOTAL" = Sheet.Name Then
    
            vDB = wbTarget.Sheets(Sheet.Name).Range("b3:i102")
    
            With vDB
            .ListColumns.Add
            x = .ListColumns.Count
            .Range(2, x) = "Total"
            End With
    
            sht1.Range("a" & Rows.Count).End(xlUp)(2).Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
    
        End If
    

    我收到“需要对象”错误。有什么建议?我对vba很新...

1 个答案:

答案 0 :(得分:1)

在当前代码的末尾添加以下代码行:

' adding "TOTAL" to last column on the right
sht1.Range("A1").Offset(, UBound(vDB, 2)).Resize(UBound(vDB, 1) + 1, 1).Value2 = "TOTAL"