VBA宏过滤器和复制到新选项卡

时间:2017-09-20 11:42:22

标签: excel vba excel-vba

我有一个宏,它将插入一个标记特定单元格的新列。 我希望它然后根据值创建两个选项卡。 我的宏给了我一张error 1004 invalid name的表格或图表

我的代码是

Sub Groups()
Columns("L:L").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("L2").Select
Range("L2:L" & Cells(Rows.Count, "A").End(xlUp).Row).Formula = "=IF(OR(RC[-1]=27594,RC[-1]=27601),""Flag"",""Groups Excluding Flag"")"
Range("L1").Select
ActiveCell.FormulaR1C1 = "Test"
Columns("L:L").Select
   Selection.Copy
   Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
      :=False, Transpose:=False

Dim c As Range
Dim rng As Range
Dim LR As Long

    LR = Cells(Rows.Count, "A").End(xlUp).Row
    Set rng = Range("A1:Q" & LR)

   Range("L2:L" & LR).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("AM1"), _ 
Unique:=True
   Columns("L:L").Select
   Selection.Copy
   Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
      :=False, Transpose:=False

   For Each c In Range([AM2], Cells(Rows.Count, "AM").End(xlUp))
    With rng
        .AutoFilter
        .AutoFilter Field:=5, Criteria1:=c.Value
        .SpecialCells(xlCellTypeVisible).Copy
        Sheets.Add After:=Sheets(Sheets.Count)
        ActiveSheet.Name = c.Value
        ActiveSheet.Paste
    End With
Next c

End Sub

3 个答案:

答案 0 :(得分:0)

我很确定问题出在这行代码Sheets.Add(After:=Sheets(Sheets.Count)).Name = c.Value如果我没记错的话,excel不希望你添加一张表并将其命名为同一行码。我建议创建和引用这样的表格

Dim ws1 As Worksheet
Dim ws2 As Worksheet
    Set ws1 = Sheets.Add(After:=Sheets(Sheets.Count))
    Set ws2 = Sheets.Add(After:=Sheets(Sheets.Count))
    ws1.Range("A1").Value = "WS1"
    ws2.Range("A1").Value = "WS2"

答案 1 :(得分:0)

Sheets.Add(After:=Sheets(Sheets.Count)).Name = c.Value更改为以下内容:

With ThisWorkbook
    Dim oW As Worksheet: Set oW = .Sheets.Add(After:=.Sheets(.Sheets.Count))
    oW.Name = c.Value
End With
oW.Paste

答案 2 :(得分:0)

我认为您需要在粘贴之前添加并重命名新工作表:

cdo mul -setctomiss,0 -ltc,0.04 dqx.nc soil_moisture.nc masked_soil_moisture.nc 

希望得到这个帮助。