代码之家  ›  专栏  ›  技术社区  ›  Idrawthings

从一系列单元格中添加列

  •  0
  • Idrawthings  · 技术社区  · 9 年前

    我有以下代码来添加一系列单元格中的行:

    enter image description here

    Sub Insert_Matrix_Rows()
        Dim Lr As Integer, Fr As Integer
    
        Fr = Columns("B").Find(What:="User R", After:=Range("B9")).Row 'Searching row of "User R" header
        Lr = Range("B" & Fr).End(xlDown).Row 'Searching last row in Risk table
    
        Rows(Lr + 1).Insert Shift:=xlDown 'Inserting new row
       'Cells(Lr + 1, "B") = Cells(Lr, "B") + 1 'Adding a sequential number
        Rows(Lr).Copy 'Copying format of last row
        Rows(Lr + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
        Application.CutCopyMode = False 'Deactivating copy mode
        Cells(Lr + 1, "C").Select
    End Sub
    

    我试图将代码翻译为适用于列,但遇到了错误(类型不匹配):

      Sub Insert_Matrix_Columns()
        Dim Lc As Integer, Fc As Integer
    
        Fc = Columns("D").Find(What:="User C", After:=Range("E6")).Column 'Searching row of "User C" header
        Lc = Range("E" & Fr).End(xlRight).Column 'Searching last row in Risk table
    
        Columns(Lc + 1).Insert Shift:=xlRight 'Inserting new row
       'Cells(Lr + 1, "B") = Cells(Lr, "B") + 1 'Adding a sequential number
        Columns(Lc).Copy 'Copying format of last row
        Columns(Lc + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
        Application.CutCopyMode = False 'Deactivating copy mode
        Cells(Lc + 1, "E").Select
    End Sub
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   avb    9 年前

    代替

    Fc = Columns("D").Find(What:="User C", After:=Range("E6")).Column
    

    具有

    Fc = Rows(6).Find(What:="User C", After:=Range("E6")).Column
    

    以下是工作代码(我复制了表格),使用:

    Sub Insert_Matrix_Columns()
        Dim lastCol As Range
    
        Set lastCol = Rows(6).Find(What:="User C").End(xlToRight).EntireColumn
    
        Columns(lastCol.Column + 1).Insert Shift:=xlShiftToRight
        lastCol.Copy
        Columns(lastCol.Column + 1).PasteSpecial Paste:=xlPasteFormats
    
        Application.CutCopyMode = False
    End Sub
    

    代码的主要问题是使用 xlRight 而不是 xlShiftToRight xlToRight 分别为-4152、-4161、-4161