道歉,如果这似乎是重复的,但我正在寻找一个特定的解决方案,可能是一个常见的问题。
我有以下代码来添加一系列单元格中的行:
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
我将其指定为宏,它可以复制第9行,并将其粘贴到该行下方。基本上,我想为列复制此过程。因此,在生成列时可以包含上面代码可能生成的任何行,反之亦然。
我试图将代码转换为适用于列但我遇到错误(类型不匹配):
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
答案 0 :(得分:0)
替换
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