Printing an array of worksheets in Excel - excel

The below code attempts to print worksheets across multiple workbooks.
Dim wb1, wb2, wb3 as workbook
set wb1 = workbooks.open(......)
set wb2 = workbooks.open(......)
set wb3 = workbooks.open(......)
Sheets(Array(wb1.Sheets(...),wb2.Sheets(...),wb3.Sheets(...))).PrintOut
There's a TypeMismatch error in my runs on the last line. What am I Mismatching?

As written in the Office VBA Reference, the Sheets-Object refers to
A collection of all the sheets in the specified or active workbook.
Therefore it will not be possible to print sheets from different workbooks together in one print task. Moreover, the syntax ist Sheets(Index) so therefore the index or the name of the sheet has to be passed.
Sub testPrint()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim s(1) As Worksheet
Dim mySheet As Variant
'
' collect sheets from different workbooks
'
Set wb1 = Workbooks("wm1.xlsm")
Set wb2 = Workbooks("wm2.xlsm")
Set s(0) = wb1.Sheets(1)
Set s(1) = wb2.Sheets(1)
'
' print or print preview sheets after each other
'
For Each mySheet In s
mySheet.PrintPreview
Next
End Sub
If You want to print multiple sheets from one workbook in a single print task, You may select them and then print all selected ones.

Related

copying sheets from multiple workbooks to existing workbook- VBA

I am trying to copy 4 sheets from 4 different workbooks into the 'Master' workbook that I am in
The below code just does it for one sheet but I want to do it for all 4 sheets
Also, currently the code below opens up the source sheet but I don't want to open source sheets. If I remove '.Open" from below file path then it says subscript out of range
Thanks
Sub Copysheets()
Dim source As Workbook
Dim Master As Workbook
Set source = Workbooks.Open("\\filepath\filename.xlsx")
Set Master = Workbooks.Open("\\filepath\filename.xlsm")
Dim sourcesheet As Worksheet
For Each sourcesheet In source.Sheets
sourcesheet.Copy After:=Master.Sheets(Master.Sheets.Count)
Next
End Sub
If you have a task that you need to do repeated times, usually it's a good idea outsource the task to a subroutine.
The following routine gets 2 parameters, the first is the master (the workbook where you want to copy the sheets into) and a filename (with the name of the file to be opened and copied). This copy-routine doesn't care about your business logic, it simply copies the sheets:
Sub Copysheets(masterWB As Workbook, sourceWBName As String)
Dim sourceWB As Workbook, sourceSheet As Worksheet
Set sourceWB = Workbooks.Open(sourceWBName)
For Each sourceSheet In sourceWB.Sheets
sourceSheet.Copy After:=masterWB.Sheets(masterWB.Sheets.Count)
Next
' Don't forget to close the file afterwards:
sourceWB.Close SaveChanges:=False
End Sub
You could then call the the routine like this (this piece of code handles your business logic but doesn't care about how the copy is done):
Sub CopySheetsFrom4Workbooks()
Dim masterWB As Workbook
Set masterWB = Workbooks.Open("\\filepath\filename.xlsm")
Copysheets masterWB, "\\filepath\filename1.xlst"
Copysheets masterWB, "\\filepath\filename2.xlst"
Copysheets masterWB, "\\filepath\filename3.xlst"
Copysheets masterWB, "\\filepath\filename4.xlst"
masterWB.Save
End Sub
or, for example, use a loop to copy sheets of all files:
Sub CopyAllMyWorkbooks()
Dim masterWB As Workbook
Set masterWB = Workbooks.Open("\\filepath\filename.xlsm")
Dim sourceFilename As String
sourceFilename = Dir("\\filepath\filename*.xlst")
Do While sourceFilename <> ""
Copysheets masterWB, sourceFilename
sourceFilename = Dir
Loop
End Sub

Copy Sheet1 in Active Workbook to Sheet 2 in Workbook named in Cell of Active Workbook Sheet 2

I have a series of Workbooks that I continually need to copy Sheet1 of a workbook to Sheet2 of the new workbook. The names of the Workbooks will advance in number (name_May2011_2, name_May2011_3, name_May2011_5). The digit on the end will change, not necessarily in sequence. I have code that allows me to list the active workbooks in a new sheet. I need to reference a cell in that sheet as the name of the Workbook as the destination top copy. My code is as follows so far:
[code]
Sub Copy_Merge()
'Declare variables and data types
Dim Wb As Workbook
Dim Ws As Worksheet
Dim i As Single, j As Single
'Create a new worksheet and save to object ws
Set Ws = Sheets.Add
'Go through open workbooks
For j = 1 To Workbooks.Count
'Save workbook name to cell A1 and downwards
Range("A1").Cells(j, 1) = Workbooks(j).Name
'Iterate through worksheets in given workbook
For i = 1 To Workbooks(j).Sheets.Count
'Save worksheet names to cell B1 and cells further right
Range("A1").Cells(j, i + 1) = Workbooks(j).Sheets(i).Name
'Continue with next worksheet
Next i
'Continue with next workbook
Next j
'This is the part I'm having issues with
'I need to set variable in cell A2 of Sheet 2 of Active Workbook as a string
'and use that string as the Workbook destination name
Dim SB As Workbook
Dim Ss As Worksheet
Set SB = ThisWorkbook
Set Ss = ThisWorkbook.Sheet("Sheet2")
Set MyToday = SB.Ss.Range("A2").Value 'name of destination workbook
Sheets("Sheet1").Select
Sheets("Sheet1").Copy Before:=Workbooks(MyToday).Sheets(3)
On Error Resume Next
ActiveSheet.Name = "Sheet2"
On Error GoTo 0
End Sub
[/code]
I've been working on this for a few days, I'm relatively new to writing macro's, and I'm at my whit's end. Can someone help with this code or suggest a better code to use?
In order to retrieve the target workbook's name from cell "A2" of "Sheet2" of your current workbook and use it to assign the respective workbook to an object, you could use:
Dim SourceWorkbook As Workbook ' Your SB
Dim SourceWorksheet As Worksheet ' Your Ss
Dim TargetWorkbook As Workbook
Dim TargetWorksheet As Worksheet
Dim TargetWorkbookName As String
Dim TargetSheetName As String
Set SourceWorkbook = ThisWorkbook
Set SourceWorksheet = SourceWorkbook.Sheets("Sheet2") ' the "s" in "Sheets" is important to access the Workbook's Sheet-Collection
TargetWorkbookName = SourceWorksheet.Range("A2").Value ' TargetWorkbookName is of type "String", thus "Set" is not allowed
Set TargetWorkbook = Workbooks(TargetWorkbookName)
TargetSheetName = SourceWorksheet.Range("B2").Value
Set TargetWorksheet = TargetWorkbook.Sheets(TargetSheetName)

How to use a dim as a file name inside workbooks() formula

I am trying to create a macro that will copy a range from one open sheet (Original.xlsx) to another open sheet (Destination.xlsx). The tricky part is I want the user to be able to name the origin excel filename (without the .xlsx at the end) via inputbox and I am having trouble with combining the dim with the copy function.
Dim wbdest As Workbook
Dim X As Variant
X = InputBox("Workbook from name?")
Set wbdest = Workbooks(X & ".xlsx")
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
Workbooks("destination.xlsx").Worksheets("Sheet1").Range("A2").PasteSpecial Paste:=xlPasteValues
The input box in this example will be input with "Original"
I am getting a Runtime error 9, subscript out of range on
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
Replace:
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
with:
wbdest.Worksheets("Sheet1").Range("A2:K25").copy
(there may be other errors in your posted code)
Your be best of doing it like this;
Sub test()
Dim wb1 As Workbook 'declare the workbook
Dim wb2 As Workbook 'declare the workbook
Dim strFile As String
strFile = InputBox("Workbook from name?") 'open up input box for user to type in what workbook they want to copy
Set wb1 = Workbooks(strFile & ".xlsx") 'set the user defined workbook by name
Set wb2 = Workbooks("Destination.xlsx") 'set the destination workbook by name
wb2.Worksheets("Sheet1").Range("A2:K25").Value = wb1.Worksheets("Sheet1").Range("A2:K25").Value 'put the value from userdefined workbook into destination
End Sub
Try and avoid copy and pasting if you can :)

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

Type Mismatch - Copy range from one workbook to another

I am trying to copy a range from one workbook to another, using the code below. The other posts similar to this issue on here and elsewhere seem to be confined to specific syntax errors which aren't relevant (as far as I'm aware) to my specific case (last line of my code). For anyone generally trying to copy and paste a given range (hard-coded) between workbooks, this may be relevant:
Sub ImportT12Accounts()
'
' ImportT12Accounts Macro
' Pulls in the list of account numbers from a report of the user's choice.
'
'
Dim fileChoice As Integer
Dim filePath As String
Dim sheetName As Variant
Dim ws0 As Worksheet 'this workbook's 2nd tab
Dim ws1 As Worksheet 'the opened workbook's 2nd tab
Dim wb0 As Workbook 'this workbook (the log)
Dim wb1 As Workbook 'the opened T12 sheet
Dim rng0 As Range 'the range of cells in this workbook's 2nd sheet to be copied to
Dim rng1 As Range 'the range of cells from the openeed workbook to be copied from
Set ws0 = ActiveSheet
Set wb0 = ActiveWorkbook
Set rng0 = Range("B9:B159")
'Find the desired T12 workbook filepath
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
fileChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If fileChoice <> 0 Then
'get the file path selected by the user
filePath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
End If
'Set variables using the newly-opened workbook
Set wb1 = Workbooks.Open(filePath)
Set ws1 = ActiveSheet
Set rng1 = Range("A9:A159")
'Use the filepath selected by User in formulas to pull the account numbers into this book, in Sheet 2
Workbooks(wb0).Worksheets(ws0).Range(rng1).Value = _
Workbooks(wb1).Worksheets(ws1).Range(rng0).Value
End Sub
When run, it throws the "Run-time error '13': Type mismatch" error on the last line, "Workbooks(wb0)...Range(rng0).Value".
I have tried subbing out this copy-paste method for a few others, without avail. For example, I have tried subbing out the range variables .Range(rng0) and .Range(rng1) with/for .Range("A9:A159") and .Range("B9:B159") directly, but get the same error.
Another example of a method I tried is:
Workbooks(wb1).Worksheets(ws1).Range(rng1).Copy
Destination:=Workbooks(wb0).Worksheets(ws0).Range(rng0)
But this gave me the same error.
I have a feeling the mismatch is being caused by one of the workbook or worksheet variables, however, I can't figure out why this would be the case. From what I can tell, it is fine to pass workbook, worksheet, and range variables into their respective methods.
This seems to be a misunderstanding of objects. The error occurs because you are passing the objects in to a string field which results in "type mismatch". The objects can be called directly and they are fully qualified as declared. You don't need to stack them like that.
Sub ImportT12Accounts()
'
' ImportT12Accounts Macro
' Pulls in the list of account numbers from a report of the user's choice.
'
'
Dim fileChoice As Integer
Dim filePath As String
Dim sheetName As Variant
Dim ws0 As Worksheet 'this workbook's 2nd tab
Dim ws1 As Worksheet 'the opened workbook's 2nd tab
'Dim wb0 As Workbook 'this workbook (the log)
Dim wb1 As Workbook 'the opened T12 sheet
Dim rng0 As Range 'the range of cells in this workbook's 2nd sheet to be copied to
Dim rng1 As Range 'the range of cells from the openeed workbook to be copied from
'Set wb0 = ActiveWorkbook
Set ws0 = ActiveSheet
Set rng0 = ws0.Range("B9:B159")
'Find the desired T12 workbook filepath
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
fileChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If fileChoice <> 0 Then
'get the file path selected by the user
filePath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
End If
'Set variables using the newly-opened workbook
Set wb1 = Workbooks.Open(filePath)
Set ws1 = ActiveSheet
Set rng1 = ws1.Range("A9:A159")
'Use the filepath selected by User in formulas to pull the account numbers into this book, in Sheet 2
rng1.Value = rng0.Value
End Sub

Resources