Search code examples
excelsendkeysvba

VBA - CopyPasteCode with Sendkeys


I'm using IDE in a excel workbook and trying to do the below code.

Sub cpypaste()    
    Range("E7").Select    
    SendKeys ("^c"), True    
    Application.Wait (Now + TimeValue("00:00:01"))    
    Range("G7").Select        
    SendKeys ("^v"), True    
End Sub

Not that I do not know alternate ways of doing it, but just curious why this is not working. I've tried running this code with keyboard shortcut and cmdbutton as well. Any help will be greatly appreciated.


Solution

  • Using sendKeys is fecal at best. I assume you are starting the code from the code window, and because of this, the commands are trying to refer to that window. Excel needs to be activated to receive the commands.

    Sub cpypaste()
    AppActivate Application.Caption 'Activates the window.
    Range("E7").Select
    
    SendKeys String:="^c", Wait:=True
    
    Application.Wait (Now + TimeValue("00:00:01"))' this line I belive is not needed, with the wait as true.
    Range("G7").Select
    SendKeys String:="^v", Wait:=True
    
    End Sub