Excel vba - printing (array) - arrays

quick question on why the below vba for printing won't work... If I have it set up individually (Sheet1.PrintOut) it prints out fine, but if I do it as array(Sheet1, Sheet2, Sheet3).PrintOut it doesn't work. Can anyone explain why?
Sub printnow()
Dim Sheet1 As Worksheet
Dim Sheet2 As Worksheet
Dim Sheet3 As Worksheet
With ThisWorkbook
Set Sheet1 = .Sheets("database1")
Set Sheet2 = .Sheets("database2")
Set Sheet3 = .Sheets("database3")
'Setting up the print setup
Sheet3.PageSetup.PaperSize = xlPaperLegal
Sheet3.PageSetup.Orientation = xlPortrait
'Print
End With
Array(Sheet1,Sheet2.Sheet3).PrintOut Copies:=1
End Sub

The Array function call returns a Variant() containing Sheet1, Sheet2, and Sheet3. A Variant() doesn't have a .PrintOut method - it isn't an object. If you want to call .PrintOut on each of the objects in the array, just loop over it:
Dim sheet As Variant
For Each sheet In Array(Sheet1, Sheet2, Sheet3)
sheet.PrintOut Copies:=1
Next

You can pass an array of sheet names to Sheets and it will process them.
Sheets(Array("database1", "database2", "database3")).Printout Copies:=1
You can also use the Sheet.Name:
Sheets(Array(Sheet1.Name, Sheet2.Name, Sheet3.Name)).Printout Copies:=1
Or you can use the sheet's indices:
Sheets(Array(1,2,3)).Printout Copies:=1

Related

Create a VBA Array from Column Headers?

I have a an export "NewExport" that always randomizes the columns of data I receive. I need these columns to align with the order of columns in "TheOrder", so this code will help to re-organize the export to align with the column headers I've already built.
I have 132 columns that need re-alignment, and while I can type it all out, there must be an easier way to align with the column headers I've already created. It should be noted that the below code is shamelessly copy/pasted from another StackOverflow answer.
Sub OrderColumns(ByVal NewExport As Workbook, ByVal TheOrder As Worksheet)
Dim correctOrder() As Variant
Dim lastCol As Long
Dim headerRng As Range, cel As Range
Dim mainWS As Worksheet
Set mainWS = NewExport.Worksheets("Sheet1")
'Need to figure out how to make this an array based on a Range
correctOrder() = Array(TheOrder.Range("A1:A132").Value)
With mainWS
lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set headerRng = .Range(.Cells(1, 1), .Cells(1, lastCol))
End With
Dim newWS As Worksheet
Set newWS = Ninja.Sheets.Add
newWS.Name = "Rearranged Sheet"
Dim col As Long
With newWS
For col = 1 To lastCol
For Each cel In headerRng
If cel.Value = correctOrder(col - 1) Then
mainWS.Columns(cel.Column).Copy .Columns(col)
Exit For
End If
Next cel
Next col
End With
End Sub
While it's not as automated as I would have liked (and requires one piece of hard-coding), I was able to find a solution as such:
Dim correctOrder(132) As Variant
'132 will need to be changed if there's ever any more/less columns added/excluded
For i = 1 To 132
correctOrder(i - 1) = TheOrder.Range("A" & i).Value
Next
This solution gave me the array I was looking for for use later on.
I recently wrote a 'column finder' function for a project of mine.
I've modified it to suit your requirements below.
The function requires you pass the workbook your correct ordered headings are in to capture. You could modify this to require your TargetWorksheet instead so it's a bit more dynamic.
The function returns a single dimension Array.
The function finds the last used Column in the Target Worksheet allowing for changes in the number of column headings (as mentioned in your own answer which has the column number hard coded).
Public Function CorrectOrderHeadingsArrayFunction(ByRef TargetWorkbook As Workbook) As Variant()
With TargetWorkbook.Sheets(1) 'Change this to target your correct sheet
Dim LastColumn As Long
LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
CorrectOrderHeadingsArrayFunction= Application.Transpose(Application.Transpose(.Range(.Cells(1, 1), .Cells(1, LastColumn)).Value)) 'This returns the array as single dimension rather than 2D
End With
End Function
As an example, below is some sample 'Test' code to show the concept of using this function .
You could call it like so, and loop through each element perhaps comparing another arrays elements to the correct order elements and do something when the correct order value is found.
Sub TestSub()
Dim CorrectOrderArray As Variant
Dim TargetCorrectOrderElement As Variant
Dim RandomOrderArray As Variant
Dim TargetRandomOrderElement As Variant
CorrectOrderArray = CorrectOrderHeadingsArrayFunction(Workbooks("Export (4).csv")) 'Change this to target your correct workbook
RandomOrderArray = Sheet1.Range("A1:AZ1000") 'Change this to target the correct range for your data.
For Each TargetCorrectOrderElement In CorrectOrderArray
For TargetRandomOrderElement = LBound(RandomOrderArray) To UBound(RandomOrderArray)
If RandomOrderArray(TargetRandomOrderElement) = TargetCorrectorderValue Then
'Do some code to write that column to your worksheet
Exit For 'Leaves the current iteration of the random order array loop to go to the next iteration of the correct order array
End If
Next TargetRandomOrderElement
Next TargetCorrectOrderElement
End Sub

Create One-Dimensional array from evaluate

Background:
I'm trying to loop through a series of sheets in a workbook from an Array given certain sheets names.
Code
Instead of the more conventional:
Sub test()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3"))
Debug.Print ws.Name
Next ws
End Sub
I'm using a different method that makes it all a bit easier to extend the array to like 10 worksheets, or start at another number, like so:
Sub test()
Dim ws As Worksheet
Dim arr As Variant: arr = ["Sheet"&ROW(1:3)]
For Each ws In ThisWorkbook.Sheets(arr)
Debug.Print ws.Name
Next ws
End Sub
Problem:
However ["Sheet"&ROW(1:3)] will create a two-dimensional array which will throw an Error 13 on the start of the For each... loop because the array expects a one-dimensional array.
I can addres this problem using a simple TRANSPOSE like:
Sub test()
Dim ws As Worksheet
Dim arr As Variant: arr = [TRANSPOSE("Sheet"&ROW(1:3))]
For Each ws In ThisWorkbook.Sheets(arr)
Debug.Print ws.Name
Next ws
End Sub
Question:
Maybe my brain is tired but right now I fail to understand why ["Sheet"&ROW(1:3)] would not create a one-dimensional array. Does anybody know?
I'm afraid the answer is simple, and I'll have one of those "Ahaaaa" moments.
In Short:
ROW(1:3) is a Range. Ranges that contain more than one cell are two dimensional arrays. Thus you get a two dimensional return.

Populate array with unique values from a filtered column with multiple values

I am trying to populate an array with values from a column in a filtered Excel table.
In this column, the values may appear multiple times, but I need to return unique values, not all occurrences of each value.
Column F
a
a
a
b
c
c
a
b
d
The array would have a variable length and, based on the sample column would have the elements: {a, b, c, d}
The length of the array cannot be fixed because my function works with a filtered table that varies in length. Sometimes there may be only one unique value, other times there might be three.
I need to do this because my array will be used to determine the subject of an e-mail with, "... " & Array.
How do I extract unique values in a column to the array?
Use Scripting.Dictionary
You can select all the data from a column with sht.Cells(sht.Rows.Count, "F").End(xlUp).Row and then use a Scripting.Dictionary to find your unique values. Here's the code:
'Main Routine
Sub MyMacro()
Dim sht As Worksheet
Dim column As Range
Dim LastRow As Long
Dim uniqueValues() As Variant
Set sht = ActiveSheet 'Set your sheet here
LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row
Set column = Range("F1:F" & LastRow)
uniqueValues = getUniqueValues(column)
'Do what you need to do with your values [...]
End Sub
'Return unique values from a Range
Function getUniqueValues(column As Range)
Dim dict As New Scripting.Dictionary ' requires "Microsoft Scripting Runtime"
Dim cell As Range
For Each cell In column
dict(cell.Value) = "1"
Next
'A double Transpose will put your data in an Array() format
getUniqueValues = Application.Transpose(Application.Transpose(dict.Keys))
End Function
If you don't want to import Microsoft Scripting Runtime, use this code for dict declaration:
'If you don't want to import Scripting Runtime, use this code
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
Note: This is tested and works perfectly.
I hope this helps.
you can use Scripting.Dictionary for such task and xlCellTypeVisible, example:
Sub sometest()
Dim x As Long, cl As Range
Dim dic As Object: Set dic = CreateObject("Scripting.Dictionary")
dic.comparemode = vbTextCompare
x = Cells(Rows.Count, "A").End(xlUp).Row
For Each cl In Range(Cells(2, "A"), Cells(x, "A")).SpecialCells(xlCellTypeVisible)
If Not dic.exists(cl.Value) Then
dic.Add cl.Value, Nothing
End If
Next cl
Debug.Print Join(dic.keys, ",")
End Sub
test:

Delete all contents except for first row for specific sheets in Excel

Please assist. I have this code here and it works for first sheet however, does not execute in the 2nd sheet. I think i'm missing a sheet syntax. thanks.
Dim arrSheets As Variant, sht As Variant
arrSheets = Array("tl_1", "tl_2")
For Each sht In arrSheets
Sheets(sht).UsedRange.Offset(1).ClearContents
Next sht
My 2 cents: do not rely on worksheet names. Instead, work with their (Name) property as seen from the Visual Basic Editor. Note that you can give significant names yourself instead of the default Sheet1..N ones. This way, your code will survive modifications to the names as seen from Excel, in the tabs at the bottom.
Option Explicit
Public Sub DoTheClearThing()
Dim loopVariant As Variant
Dim loopWorksheet As Excel.Worksheet
Dim worksheetsToConsider As Variant
'Use the (Name) property, as seen from the Visual Basic Editor, of the worksheets you're interested in.
'The array below is not a string array; it is an array of worksheet objects.
worksheetsToConsider = Array(TL_1, TL_2)
'The For's variable must be a Variant; you can then Set it to a variable of the Worksheet type and enjoy Intellisense.
For Each loopVariant In worksheetsToConsider
Set loopWorksheet = loopVariant
loopWorksheet.UsedRange.Offset(1).ClearContents
Next
End Sub
Here's what the worksheets' (Name) properties look like in my test Excel workbook:
From within your workbook's code, you can directly interact with worksheet objects using their (Name) property. Avoid ThisWorkbook.Worksheets("tl_1").SomeMethod and directly go with TL_1.SomeMethod. By the way, a worksheet's (Name) property can be read by code using its CodeName property.
Option Explicit
'This will do something to your target sheets,
'just make sure your "something" is what you want
Dim N As Long
Dim wsName As String
'Optional if included
For N = 1 To ThisWorkbook.Sheets.Count
wsName = ThisWorkbook.Worksheets(N).Name
If wsName = "tl_1" or wsName = "tl_2" Then
ThisWorkbook.Worksheets(N).UsedRange.Offset(1).ClearContents
Else 'Do Nothing
End If
Next N
Note: This is very worksheet name dependent and users can change those if you are not the only user. You may want to CodeName your sheets (properties Explorer and change the Name) then pull the CodeName.
You can use an array to hold the sheets names but it seems like more trouble than its worth unless you are going to load the names into the array.
-WWC
Worksheet.UsedRange does not always return the correct address. Consider the results of the test below:
Test Used Range
Sub Test()
Application.ScreenUpdating = False
Dim cell As Range, target As Range
Debug.Print "Data Range", "|"; "UsedRange"
Debug.Print String(24, "_")
With Worksheets.Add
Set target = .Range("B2:D2")
target.Value = 1
Debug.Print target.Address, "|"; .UsedRange.Address
End With
With Worksheets.Add
.Range("A1:G10").Interior.Color = 65535
Set target = .Range("B2:D2")
target.Value = 1
Debug.Print target.Address, "|"; .UsedRange.Address
End With
End Sub
Clear Non-Headers
Sub ClearNonHeaderRows()
Dim arrSheets As Variant, sht As Variant
Dim cell As Range
arrSheets = Array("tl_1", "tl_2")
For Each sht In arrSheets
With Worksheets(sht).UsedRange
Set cell = .Find("*", .Cells(1, 1))
If Not cell Is Nothing Then
cell.Offset(1).Resize(.Cells.Rows.Count - cell.row + .Cells(1, 1).row).EntireRow.ClearContents
End If
End With
Next sht
End Sub

Tying an Array of worksheets to a specific workbook

The goal of my macro is from a large set of data, divide the data into separate workbooks for each product. After I paste only the specific data into the file, I want to copy 5 separate worksheets from the workbook with all of the data, each worksheet with a pivot table on them, set the data on the pivot table to the data on the spread sheet that I copied over previously. Then refresh the pivot tables.
My biggest question is how to I name an array of worksheets to a work book
Dim cell As Range, DataRng As Range
Dim curPath As String, curWB As String, newWB
Dim ArrayCM As Variant
Dim InxW As Long
Dim xTable As PivotTable
curPath = ActiveWorkbook.Path & "\"
curWB = ActiveWorkbook.Name
'Array of worksheets to be copied over for Company Manger
Set ArrayCM = curWB.Sheets(Array("CM YTD", "CM MTD", "CM Refurb", "TBM Local", "PSM"))
--This Gives me an error
Because I'm going to creating several workbooks, I want to define my array to copy over from the master file to the new file. Help on this would be greatly appreciated.
You can create a worksheet type var as an array, redim it and assign each element within the array to a Worksheet Object.
Sub manyWSs()
Dim w As Long
Dim cwb As Workbook
Dim wss() As Worksheet
Set cwb = ThisWorkbook
With cwb.Worksheets(Array("Sheet1", "Sheet3", "Sheet5"))
ReDim wss(1 To .Count)
For w = 1 To .Count
Debug.Print .Item(w).Name
Set wss(w) = .Item(w)
Next w
End With
For w = LBound(wss) To UBound(wss)
Debug.Print wss(w).Cells(1, 1).Address(0, 0, external:=True)
Next w
End Sub
The Worksheets(Array("Sheet1", "Sheet3", "Sheet5")) is not a true Worksheets collection so .Item(w) is used to pick out the pieces. Once each piece has been Set, all the properties, methods and members of a single Worksheet Object are available to each piece of the array with full parent Workbook object association.

Resources