macros将一个范围复制到另一个范围,作为值和公式

请填写以下代码所需的代码:

我需要创build一个macros来复制范围L18:L20并将公式粘贴到相应的列(M18:M20)中。 然后我需要使用特殊粘贴,并复制和粘贴范围M18:M20的值L18:L20。

然后我需要这样的循环,所以当我运行macros时,M18:M20中的公式将被复制并粘贴到N18:N20中,然后从N18:N20复制粘贴到M18:M20等等。

这是我的代码:

Sub Macro1() Range("L18:L20").Copy Range("M18:M20").PasteSpecial Paste:=xlPasteFormulas, _ Operation:=xlNone, _ SkipBlanks:=False, _ Transpose:=False Range("M18:M20").Copy Range("L18:L20").PasteSpecial Paste:=xlPasteValues, _ Operation:=xlNone, _ SkipBlanks:=False, _ Transpose:=False End Sub 

试试这个:

 Sub test_Andrew() Dim Ws As Worksheet, _ LastCol As Integer Set Ws = ActiveSheet With Ws LastCol = .Cells(18, .Columns.Count).End(xlToLeft).Column .Range(.Cells(18, LastCol), .Cells(20, LastCol)).Copy .Cells(18, LastCol + 1).PasteSpecial Paste:=xlPasteFormulas, _ Operation:=xlNone, _ SkipBlanks:=False, _ Transpose:=False .Range(.Cells(18, LastCol + 1), .Cells(20, LastCol + 1)).Copy .Cells(18, LastCol).PasteSpecial Paste:=xlPasteValues, _ Operation:=xlNone, _ SkipBlanks:=False, _ Transpose:=False End With End Sub 

尝试这个:

 Sub Macro1(colindex As Integer) ' ' Macro1 Macro ' 'make our ranges variable and based on the input column Dim range_alpha As Range, range_beta As Range Set range_alpha = ActiveSheet.Range(ActiveSheet.Cells(18, colindex), ActiveSheet.Cells(20, colindex)) Set range_beta = ActiveSheet.Range(ActiveSheet.Cells(18, colindex + 1), ActiveSheet.Cells(20, colindex + 1)) range_alpha.Select range_alpha.Select Selection.Copy range_beta.Select Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False range_beta.Select Application.CutCopyMode = False Selection.Copy range_alpha.Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False Range("M18:M20").Select End Sub Sub Macro1_BySelection() '' use this sub to call Macro 1 if you want to select a column first Macro1 Selection.Column End Sub Sub Macro1_ByProbe() '' use this sub to call Macro 1 for the first empty column found Dim tst As String Dim colindex As Integer colindex = 1 tst = ActiveSheet.Cells(18, colindex).Value Do While tst <> "" colindex = colindex + 1 tst = ActiveSheet.Cells(18, colindex).Value Loop Macro1 colindex End Sub Sub Macro1_ByR3uk() Dim LastCol As Integer LastCol = ActiveSheet.Cells(18, ActiveSheet.Columns.Count).End(xlToLeft).Column Macro1 LastCol + 1 End Sub 

您的初始function已经被调整为不是在“Lxx”的固定范围内操作,而是接受一个数字作为列索引。

另外两个macros提供了确定使用哪个范围的两种不同的方法:

  • Macro1_BySelection()使用macros被调用时select的单元格。
  • Macro1_ByProbe()testingfind第一个空列。
  • 编辑:我喜欢R3ukfind最后使用的列比我的方式,用他的技术macro1_ByR3uk() (我们学习每一天:-))