下面的VBA代码粘贴不同的值与复制的值。
例如:下面的代码复制单元格(11,13).Formula "=SUM(M12:M13)"到Cells(11,14).Formula,在复制和xlPasteFormulas粘贴到Cells(11,14). Cells(11,14)公式后变成"=SUM(N12:N13) .Does,有人知道为什么吗?但结果是预期的。
For x = A_OFFSET_MARKETVALUE To A_OFFSET_CURRENT
Cells(nLevel1Position, iColumn).Select
Selection.Copy
Cells(nLevel1Position, iColumn + x).Select
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Next x我需要优化以上代码到下面的代码。但是下面的代码给出了相同的公式值,这与预期的不一样。如何优化以上代码,但仍有与原代码相同的结果。
Cells(nLevel1Position, iColumn + x).Formula = Cells(nLevel1Position, iColumn).Formula发布于 2019-07-25 13:44:29
要“精简”这一点:
Range("M11:N11").Formula = "=SUM(M12:M13)"或者:
Range("M11:N11").Formula = Range("M11").Formula有了这种行为,Excel“知道”您想要更改引用的单元格公式。所以要利用这些内置的智慧!
在您自己的代码中,您不需要使用迭代(因为您希望将其偏移到第N列),只需进行上面的更改即可:
With ThisWorkbook.Sheets("Sheet1") 'Change accordingly
.Range(.Cells(nLevel1Position, iColumn), .Cells(nLevel1Position, iColumn + A_OFFSET_CURRENT)).Formula = .Cells(nLevel1Position, iColumn).Formula
End With在最后一种情况下,您确实需要从列M(或在您的代码中,iColumn)中使用FormulaR1C1而不是.Formula。
就像这样:
With ThisWorkbook.Sheets("Sheet1")
.Range(.Cells(nLevel1Position, iColumn + A_OFFSET_MARKETVALUE), .Cells(nLevel1Position, iColumn + A_OFFSET_CURRENT)).Formula = .Cells(nLevel1Position, iColumn).FormulaR1C1
End With在所有情况下,都没有迭代+附加的好处--没有粘贴到Excel剪贴板上的值,这将提高您的效率。
如果您确实需要源代码的格式,请尝试:
With ThisWorkbook.Sheets("Sheet1")
.Cells(nLevel1Position, iColumn).Copy
.Range(.Cells(nLevel1Position, iColumn + A_OFFSET_MARKETVALUE), .Cells(nLevel1Position, iColumn + A_OFFSET_CURRENT)).PasteSpecial (xlPasteFormats)
.Range(.Cells(nLevel1Position, iColumn + A_OFFSET_MARKETVALUE), .Cells(nLevel1Position, iColumn + A_OFFSET_CURRENT)).Formula = .Cells(nLevel1Position, iColumn).FormulaR1C1
Application.CutCopyMode = False
End With发布于 2019-07-25 13:37:38
除了前面的答案外,不使用 selection。有许多方法可以使脚本混乱,例如单击其他地方。相反,直接调用方法Copy和PasteSpecial
Cells(nLevel1Position, iColumn).Select
Selection.Copy
Cells(nLevel1Position, iColumn + x).Select
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False可以更改为
Cells(nLevel1Position, iColumn).Copy
Cells(nLevel1Position, iColumn + x).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False发布于 2019-07-25 13:46:33
如果您的目标是移动单元格引用,那么尝试以下代码:
Cells(nLevel1Position, iColumn).Copy Cells(nLevel1Position, iColumn + x)https://stackoverflow.com/questions/57203092
复制相似问题