VBA, activate workbook without explicitly naming it - excel

my code has workbook A and workbook B. I copy sheets from B to A. The issue is that both will be open, so I explicitly name each workbook.
When I paste into B I activate A by its name. Is there anyway I can activate A without using the workbook name?
'Set Current Workbook as Master
Set masterWB = Application.ThisWorkbook
'Set some Workbook as the one you are copying from
Set dailyWB = Workbooks.Open(Sheets("Control Manager").Range("O2"))
'Copy the Range from dailyWB and Paste it into the MasterWB
dailyWB.Sheets("Summary").Range("A1:BJ200").Copy masterWB.Sheets("AFS Summary").Range("A1").Rows("1:1")
'formatting and paste as values
Workbooks("Workbook B").Activate
Worksheets("Summary").Select

If you are not wanting to explicitly set your workbook, then you can always expect some room for error.
But, the following should allow you to set the alternate workbook if you only have two workbooks open - otherwise if you have more open, then this will probably not work as expected.
Dim masterWB As Workbook, dailyWB As Workbook, wb As Workbook
Set masterWB = ThisWorkbook
For Each wb In Application.Workbooks
If wb.Name <> masterWB.Name Then
Set dailyWB = wb
exit for
End if
Next
Debug.Print dailyWB.Name

Related

Macro in Personal.xlsb - Active workbook reference [duplicate]

I have a number of scripts that are in a module in my Personal.xlsb file. It's kept hidden, but in this script, the idea is that you run it from within a different workbook each time. It opens a separate workbook (source.xlsx), copies a range from it, pastes into the original workbook, and then closes source.xlsx.
When it comes to the "ThisWorkbook.ActiveSheet.Paste" part, it's pasting it into the Personal.xlsb workbook instead of the target workbook that is actually open and visible. How can I make sure it's being pasted in the right workbook? The workbook's filename will always be different, so I can't specify a path or anything like that.
Sub CopyData()
Application.DisplayAlerts = False
Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
ThisWorkbook.ActiveSheet.Paste
wbSource.Close
Application.DisplayAlerts = True
Call CopyCFormat
End Sub
Don't use ThisWorkbook in most cases, as it references the workbook that the macro is stored in (in this case, personal.xlsb).
Instead, you can use ActiveWorkbook to refer to whichever workbook has focus at the time the macro is run. You can also assign ActiveWorkbook to a variable for easier reference.
Sub CopyData()
Application.DisplayAlerts = False
Dim wbSource As Workbook
Dim wbTarget as Workbook
Set wbTarget = ActiveWorkbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
wbTarget.ActiveSheet.Paste
wbSource.Close
Application.DisplayAlerts = True
Call CopyCFormat
End Sub
You could also reference the active sheet without specifying which workbook it's in, as:
Dim wbSource As Workbook
Dim shtTarget as Worksheet
Set shtTarget = ActiveSheet
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
shtTarget.ActiveSheet.Paste
Luck!
If I understand it, you should just add another workbook variable.
Sub CopyData()
Dim mainWB As Workbook
Dim mainWS As Worksheet
Set mainWB = ActiveWorkbook
Set mainWS = mainWB.Sheets(1) ' Change this to whatever you need it to be
Application.DisplayAlerts = False
Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
mainWS.Paste
wbSource.Close
Application.DisplayAlerts = True
Call CopyCFormat
End Sub

copy from whole external worksheet to worksheet in mainbook

This code works up through the paste into sheet 2 - I can switch over to the new open workbook and see that it is in copy mode but cannot get it to paste into Sheet2(Test). I have tried both "Sheet2" and "Test" but get
run time error 9: subscript out of range
see snip below
Sub ImportWorksheet999()
Dim Wb1 As Workbook
Dim MainBook As Workbook
'Open All workbooks first:
Set Wb1 = Workbooks.Open("G:\T\TWeir\Prod Ctrl\XML Reports\BDA\BDAREPORTtest.xlsx")
Set MainBook = ActiveWorkbook
'Now, copy what you want from wb1:
Wb1.Sheets("BDA Report").Cells.Copy
'Now, paste to Main worksheet:
MainBook.Sheets("Sheet2").Range("A1").PasteSpecial
'Close Wb's:
Wb1.Close
End Sub
Set Wb1 = Workbooks.Open("G:\T\TWeir\Prod Ctrl\XML Reports\BDA\BDAREPORTtest.xlsx")
Set MainBook = ActiveWorkbook
Opening a file will make it the ActiveWorkbook, so your Wb1 and MainBook both refer to the opened workbook.
Should be
Set MainBook = ActiveWorkbook 'or ThisWorkbook if that's where the code is running
Set Wb1 = Workbooks.Open("G:\T\TWeir\Prod Ctrl\XML Reports\BDA\BDAREPORTtest.xlsx")

Excel VBA file name changes

I have to 2 Excel workbooks to work with: Book1october & Book2. Book1october18 is an import file, meaning that it changes monthly, along with the name (next month it will be Book1november18). I have to copy some data from Book1october to Book2 automatically through VBA code.
This is the code that I've written:
Windows("Book1october18").Activate
Sheets("Sheet1").Activate
Range("B2:AQ5").Select
Selection.Copy
Windows("Book2").Activate
Sheets("Sheet1").Activate
Range("R2:BG5").Select
ActiveSheet.Paste
My problem is that I don't know how to write the code in order to make the actions that I want whenever the month's name changes and also the year. (I have to make it for all the months and 2019)
You can automatically update your workbook name using the Date() function and Format()
Dim sWbName As String
sWbName = "Book1" & LCase(Format(Date, "mmmmyy"))
Debug.Print sWbName
'Prints Book1october18
The name/path of the workbook doesn't need to matter. Use K.Davis's code to come up with a filename, or prompt the user for a path/file to open - get that string into some sourceBookPath variable, then have the macro open the workbook. Now you can hold a reference to that Workbook object:
Dim sourceBook As Workbook
Set sourceBook = Application.Workbooks.Open(sourceBookPath)
Now, the worksheet.
Dim sourceSheet As Worksheet
If the sheet is always going to be named "Sheet1", then you can do this:
Set sourceSheet = sourceBook.Worksheets("Sheet1")
Or, if the sheet is always going to be the first sheet in the book (regardless of its name), you can do this:
Set sourceSheet = sourceBook.Worksheets(1)
Once you have a Worksheet object, you can get the Range you need - but first you need your target. Again if "book2" is opened by the macro, things are much simpler:
Dim targetBook As Workbook
Set targetBook = Application.Workbooks.Open(targetBookPath)
Or is it created by the macro?
Set targetBook = Application.Workbooks.Add
Anyway, we want the first sheet:
Dim targetSheet As Worksheet
Set targetSheet = targetBook.Worksheets(1)
And now we can copy from the source, and paste to the target:
sourceSheet.Range("B2:AQ5").Copy targetSheet.Range("R2:BG5")
And not once did we ever need to .Select or .Activate anything, and we never needed to care for any Window.
Replace:
Windows("Book1october18").Activate
with:
s = LCase(Format(Now, "mmmm")) & Right(Year(Now), 2)
Windows(s).Activate
Try this.
This is a recognition of the next month's document, assuming you have opened two documents.
Sub test()
Dim Wb1 As Workbook, wb2 As Workbook
Dim Wb As Workbook
For Each Wb In Workbooks
If InStr(Wb.Name, "Book1") Then
Set Wb1 = Wb
ElseIf InStr(Wb.Name, "Book2") Then
Set wb2 = Wb
End If
Next Wb
Wb1.Sheets("Sheet1").Range("B2:AQ5").Copy wb2.Sheets("Sheet1").Range("r2")
End Sub

Choose from open workbooks to paste in copied data

I am writing an VBA code that should copy a specific range from one workbook into another workbook (that is open). I want to choose this workbook from a popup window that is showing all the open excel workbooks.
What I have to start with is below which is copying the range I want, do not want to specify the workbook (changing every year) or the worksheet (changing every month) more than this. From the Application.Dialogs(xlDialogActivate).Show I get a list of active workbooks/aplications (thanks #jkpieterse) and I now want to set this as WB2 so that I can copy past it into my chosen range.
Sub GTS_Timesheet()
Dim WB As Workbook, WS As Worksheet, RG As Range, WB2 As Workbook
Set WB = ActiveWorkbook
Set WS = WB.ActiveSheet
Set RG = WS.Range("F10", Range("U" & Cells(Rows.Count, "F").End(xlUp).Row))
''Set WB2 =
RG.Copy
WB2 = Application.Dialogs(xlDialogActivate).Show
WB2.Worksheets("Paste FRW Data").Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValues
End Sub
Thanks, and please tell if I need to explain more what I want.
Once selected the workbook becomes active:
Application.Dialogs(xlDialogActivate).Show
Set WB2 = ActiveWorkbook

Switch to other workbook

I am trying to build a code which would switch to the immediate other open workbook and copy data from there.
I can use workbook(1) and workbook(2) ,but problem is this index changes by sequence of opening workbooks.
So I want to put if function in it ,but doesnt work. Below is the code.
If ActiveWorkbook = Workbooks(1) Then
Workbooks(2).Activate
Else
Workbooks(1).Activate
End If
but it gives error 438 ,object doesn't support property or method.
Can you help me debug this?
Try the code below, the last section of the Copy >> Paste is just an example how you copy Range("A1:E10") from "Sheet1" in DestWB to ThisWB "Sheet1" (without using Activate or Select) - you should be able to modify it quite easily.
Code
Option Explicit
Sub CopyThisWorkBOok()
Dim ThisWB As Workbook
Dim DestWB As Workbook
Dim wb As Workbook
Dim i As Long
i = Application.Workbooks.Count
If i <> 2 Then ' check if number of open workbooks is 2
MsgBox "You need to have 2 open workbooks, currently there are " & i & " open workbooks", vbCritical
Exit Sub
Else
For Each wb In Application.Workbooks ' loop through all open workbooks
If wb.Name <> ThisWorkbook.Name Then
Set DestWB = wb
Else
Set ThisWB = ThisWorkbook
End If
Next wb
End If
' from here you start the part where you copy >> paste, there is no need to `Activate` or `Select` anything
DestWB.Worksheets("Sheet1").Range("A1:E10").Copy Destination:=ThisWB.Worksheets("Sheet1").Range("A2")
End Sub
You can use names of target objects, for example:
Workbooks("MyBook.xls").Worksheets("Sheet1").Activate
Depending on what you are trying to do, the description is not very clear, you can use a variation of this code. You can define the workbook that contains the VBA as "ThisWorkBook" and go from there.
Dim source_worksheet As Worksheet
Set source_worksheet = ThisWorkbook.Worksheets("Sheet2")
Dim target_worksheet As Worksheet
Set target_worksheet = ActiveWorkbook.Worksheets("Sheet1")
'Defines what sheet you are copying
source_worksheet.Copy After:=target_worksheet

Resources