When I try and open a new workbook in vba - from a macro based in my Personal Macro Workbook - using:
Workbooks.Add
it systematically opens two workbooks.
When I try the same using something like:
Workbooks("book1").Activate
it rarely works because the number index after the word "book" rarely matches that of "book1".
My ultimate purpose is to automatically name the created workbook.
However, vba winds up naming the second, empty workbook rather than the first, desirable one.
I have Office 365 Home.
The full code is:
********************
Sub ExportNameAndSave()
ActiveWindow.Activate
ActiveSheet.Select
Dim lastrow As Range
Dim lastcolumn As Range
Dim refnumber As String
refnumber = Range("b4").Value
Range("A1", Range("a60000").End(xlUp)).Select
Set lastrow = Selection
Range("A1", Range("a1").Offset(0, 50).End(xlToLeft)).Select
Set lastcolumn = Selection
Range(lastrow, lastcolumn).Select
Selection.Copy
Workbooks.Add
ActiveWorkbook.Activate
ActiveWorkbook.SaveAs Filename:="D:\Common Area\" & refnumber & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
********************
Note: I have been through dozens of tips on this forum for people encountering similar problems when they open a workbook in Excel from menus. They DO NOT work.
Note that my problem is about opening a workbook using vba code.
The macro works all the way to just before Workbooks.Add
.
However, at that point, this is what happens:
1) It creates a new workbook and exports the content of the intial sheet contained in the initial workbook to this new worksheet - which is exactly what I want;
2) Then it opens a second worksheet - which is NOT what I want - and at the command "ActiveWorkbook.Activate", it selects this second undesirable workbook and actually succesfully names it and saves it.
Therefore, I have a successfully named and saved file, but it is empty of content, because the second workbook is empty. What I want is to name and save the first workbook that contains the exported content.
Note: this sub works well when I close all my Excel workbooks, when I re-open only the start workbook and when I replace the line "Workbooks.Add" with "'Workbooks("book1").Activate", for example.
However, this does not give repeatable, reliable results, for the aforementioned reasons.
Any help would be appreciated.