[英]Excel macro copy values from one row to another without overwriting formulas in the target row
[英]Macro to copy one range to another, as values and as formulas
請提供填寫此說明所需的代碼建議:
我需要創建一個宏來復制范圍L18:L20並將公式粘貼到相應的列(M18:M20)中。 然后,我需要使用特殊粘貼並復制並粘貼L18:L20范圍內的M18:M20范圍內的值。
然后,我需要使用它來進行循環排序,因此當我運行宏時,會將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
您的初始函數已經過調整,不作用於“ Lxx”的固定范圍,而是接受數字作為列索引。
另外兩個宏提供了兩種不同的方法來確定要使用的范圍:
Macro1_BySelection()
使用在調用宏時所選的單元格。 Macro1_ByProbe()
測試以查找第一個空列。 macro1_ByR3uk()
(我們每天都在學習:-))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.