我有一个按钮复制列n&我粘贴在n + 3& i + 3,但在列n& i之后我需要改为n + 3& i + 3中。我尝试通过在代码末尾添加n = n + 3
i = i + 3
来实现这一点,但它无效。
Sub Macro1()
Dim n As Integer
Dim i As Integer
n = 22
i = 24
Range(Columns(n), Columns(i)).Copy
Range(Columns(n + 3), Columns(i + 3)).PasteSpecial xlPasteAllMergingConditionalFormats
Columns(n + 3).ClearContents
n = n + 3
i = i + 3
End Sub
答案 0 :(得分:2)
另一种选择是将变量声明为Static
:
Sub Macro1()
Static n As Integer
Static i As Integer
If n = 0 Then n = 22
If i = 0 Then i = 24
Range(Columns(n), Columns(i)).Copy
Range(Columns(n + 3), Columns(i + 3)).PasteSpecial xlPasteAllMergingConditionalFormats
n = n + 3
i = i + 3
End Sub
请注意,如果您这样做,则需要添加"初始化代码"第一次运行宏。
答案 1 :(得分:1)
将变量分配给单元格。例如,您将n的值设置为单元格A1,将i的值设置为单元格B1。
Sub Macro1()
Dim n As Integer
Dim i As Integer
n = Worksheets("Sheet1").Range("A1").Value
i = Worksheets("Sheet1").Range("B1").Value
Range(Columns(n), Columns(i)).Copy
Range(Columns(n + 3), Columns(i + 3)).PasteSpecial xlPasteAllMergingConditionalFormats
Columns(n + 3).ClearContents
n = n + 3
i = i + 3
Worksheets("Sheet1").Range("A1").Value = n
Worksheets("Sheet1").Range("B1").Value = i
End Sub
答案 2 :(得分:1)
你可以试试这个
Sub Macro1()
Dim n As Integer
Dim i As Integer
With ActiveSheet.UsedRange
n = WorksheetFunction.Min(.Columns(.Columns.Count).Column - 2, 22)
End With
i = n + 2
Range(Columns(n), Columns(i)).Copy
Range(Columns(n + 3), Columns(i + 3)).PasteSpecial xlPasteAllMergingConditionalFormats
Columns(n + 3).ClearContents
End Sub