“Application.Calculation = xlCalculationManual” statement causing run-time error 1004 in VBA Copy-Paste procedure

后端 未结 2 665
孤街浪徒
孤街浪徒 2020-12-21 09:40

I have VBA code that copies the first row and pastes the values to multiple rows. The below code runs fine and pastes the rows as expected:

Sub Macro1()
  D         


        
2条回答
  •  离开以前
    2020-12-21 09:47

    Pertinent to you particular question, the answer is: Application.Calculation = xlCalculationManual statement erases the Clipboard Memory, which causes the subsequent Run-time error in your code snippet.

    Note: there is another suggested explanation as 'Excel copy loosing the focus'; it might be just a semantic difference, pointing to the same effect and just worded differently, but for better clarity I prefer this one, i.e. clipboard memory (or whatever you call that temp register) loosing value, or the reference.

    The test settings to prove/illustrate the concept and detailed explanation follows:

    'Error occured because a statement
    'Application.Calculation = xlCalculationManual
    'or Application.Calculation = xlAutomatic
    'or Application.Calculation = xlManual
    'placed after `Selection.Copy` clears the clipboard memory;
    'thus there is nothing to paste and Error 1004 occured
    'as demonstrated in the added test code block
    Sub YourMacroWithProblem()
        Dim i As Long
    
        Range("A1:M1").Select
    
        'Selected Range content is placed to Clipboard memory
        Selection.Copy
    
        'This statement erases Clipboard memory
        Application.Calculation = xlCalculationManual
    
        ' test if clipboard is empty ---------------------
        On Error Resume Next
        ActiveSheet.Paste
        If Err Then MsgBox "Clipboard is Empty": Err.Clear
        '-------------------------------------------------
    
      For i = 1 To 50
        Range("A" & i).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
          :=False, Transpose:=False
      Next i
    End Sub
    

    Also, there is an old discussion on similar topic: Stop VB from Clearing Clipboard (link: http://www.mrexcel.com/forum/excel-questions/459793-stop-vbulletin-clearing-clipboard-3.html).

    You may consider the following solution to your problem optimized for speed and reliability:

    Sub Macro2()
        Dim i As Long
    
        Application.Calculation = xlCalculationManual
        Application.ScreenUpdating = False
    
        For i = 1 To 50
            Range("A1:M1").Copy Destination:=Range("A" & i)
        Next i
    
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
    
    End Sub
    

    Note: unlike your problematic code snippet, there is no need for the Select statement and Clipboard Copy/Paste operations in suggested solution, thus any potential side effects will be minimized, either.

    Hope this may help. Kind regards,

提交回复
热议问题