I'm having trouble with Excel VBA with the following: I'm trying to open an existing empty workbook template (pn), copy data from an existing sheet (wb) and paste it into "pn", but I keep getting all kinds of error such as Error 400, Subscript out of range and constant freezing.
I've tried the code with many variations, but mostly (and in my last attempt below) the error happens in the following line:
Workbooks(pn).Sheets("data").Select
Does it have to do with VBA properly getting the opened file name or switching between workbooks? How to properly switch between different workbooks and copy/paste data?
EDIT: also, when running the code on debug mode using ("Step into") it works just fine. I've noticed that the real opened file name only appears when the code waits for the workbook to open entirely or when I alt+tab into it, else its name keeps showing as "Excel" and the error happens!
'opens template
fileName = Application.GetOpenFilename("Excel-files,*.xlsx", 1, "OPEN TEMPLATE", , False)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error GoTo Err1
Workbooks.Open (fileName)
pn = ActiveWorkbook.Name
'copy and paste between workbooks
Windows(wb).Activate
Workbooks(wb).Sheets("Info").Select
Workbooks(wb).Worksheets("Info").Range("A4:Z1000").Select
Selection.Copy 'Destination:=Workbooks(pn).Sheets("data").Cells(3, 1)
Workbooks(pn).Sheets("data").Select
Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim pn As Workbook, wp As Workbook
andSet pn = Workbooks.Open("complete path")
andSet wb = Workbooks.Open("complete path")
and then you can use them likepn.Sheets("data")
– jessi