VBA复制,过去,重命名,复制过去并贯穿每一列。

时间:2018-10-24 14:16:54

标签: excel vba excel-vba

我正在尝试构建VBA代码。有些位不起作用。工作:它正在从“客户”工作簿中收集有价值的单元格并将其粘贴到供应商工作簿中的新表中。新工作表在单元名称上重命名。无法正常工作:我还想复制供应商工作簿中名为模板的标头。最后一点,我想让VBA代码遍历每一列。

Sub Copy_Past_Repeat()

Dim rs As Worksheet
Dim rng As Range
    Windows("Customer.xlsm").Activate
    Set rng = Range("n1:n1000")   'column
    rng.SpecialCells(xlCellTypeConstants).Select   'Selecting only hardcoded data
   Selection.Copy
   Windows("Supplier.xlsm").Activate
   Sheets.Add after:=ActiveSheet
   Range("C2").Select
    ActiveSheet.Paste
     ActiveSheet.Name = ActiveSheet.Range("C2")

  'not working
   ThisWorkbook.Sheets("Template").Range("A1:E1").Select
    Selection.Copy

   ActiveSheet.Paste 'should be pasted in just crated spreadsheet Name=(C2)
   Application.CutCopyMode = False

  End Sub `

1 个答案:

答案 0 :(得分:0)

强烈建议避免使用.Select.Activate或类似动作。
参见How to avoid using Select in Excel VBA

还要始终指定范围在哪个工作表或工作簿中。否则,Excel无法识别并猜测。

Option Explicit

Sub Copy_Past_Repeat()
    Dim rng As Range
    Set rng = Workbooks("Customer.xlsm").Range("N1:N1000")   'column

    rng.SpecialCells(xlCellTypeConstants).Copy   'Copy only hardcoded data

    Dim NewWs As Worksheet
    With Workbooks("Supplier.xlsm")
        Set NewWs = .Sheets.Add(After:=.ActiveSheet) 'remember the new added sheet in NewWs so we can access it later 
        NewWs.Range("C2").Paste
        NewWs.Name = NewWs.Range("C2")

        ThisWorkbook.Worksheets("Template").Range("A1:E1").Copy

        NewWs.Paste 'should be pasted in just crated spreadsheet Name=(C2)
        'here you should specify where in the sheet to paste
        'NewWs.Range("A1").Paste
    End With

    Application.CutCopyMode = False
End Sub