Linking un-named workbook to variable in VBA - vba

I am writing a macro that will copy and paste information form one workbook into another workbook in excel 2010. The workbook that the data is in is the same workbook as the macro. I have made VBA create a new workbook to paste the data in. How do I assign the new workbook that VBA has just created to a variable.
Thanks For Any Help

You haven't mentioned exactly how you create the workbook, but you can set a reference to the new Workbook object in the same statement that creates it.
Example:
Option Explicit
Sub AddWorkbook()
Dim oWb As Workbook
Set oWb = Workbooks.Add
'Do something with the new workbook
Debug.Print oWb.FullName
Set oWb = Nothing
End Sub

try seeing names of all workbooks by iterating over Workbooks. I think the name of newly created workbook will "Workbook1" until there is already no other unnamed workbook. So basically newly created workbook is still not unnamed.

Related

VBA to copy and past in two different workbooks

I want to copy all the data and paste it in new workbook. With the below coding, I am able to paste all the values but it is creating two workbooks and pasting the data in one workbook.
I want to create only one new workbook and past the data. Not sure as to what went wrong.
On Error Resume Next
ThisWorkbook.Sheets(2).Copy
Dim wkb As Workbook
Set wkb = Workbooks.Add
wkb(1).PasteSpecial xlPasteValues
On Error GoTo 0
The Copy method has a different meaning when applied to a Worksheet and when applied to a Range:
The Copy method of a Worksheet creates a copy of the sheet; in the absence of any parameter, the copy is placed in a new workbook.
The Copy method of a Range puts a copy of the Range on the clipboard, from where you can then Paste it somewhere else.
So in your case, the statement
ThisWorkbook.Sheets(2).Copy
already makes a copy the Worksheet into a new workbook.
If you want to create the new workbook explicitly then you should copy the used range to the clipboard:
ThisWorkbook.Sheets(2).UsedRange.Copy
It's not the answer, but let me do it instead of yourself:
On Error Resume Next
ThisWorkbook.Sheets(2).Copy
Dim wkb As Workbook
Set wkb = Workbooks.Add
wkb(1).PasteSpecial xlPasteValues
On Error GoTo 0
.

Open and update an existing workbook with 2 worksheets

This may be simplistic to most of you. I just started using VBA to create and update excel workbooks. I found some code on the internet to open and update an existing workbook and worksheet. Like I said, I am brand new at this. Does this code even make sense? I just need to know how to open an existing workbook and all the examples I have found aren't working in our environment.Thanks for any help I can get
Dim wbSource, xlApp, srcWorksheet
'initialize
Set xlApp = CreateObject("Excel.Application")
'open source and target files
Set wbSource = lApp.Workbooks.Open("X:\GCIXCycleCompare_test_auto.xlsx")
set srcWorksheet = wbSource.Worksheets("NewCycle")
srcWorksheet.sheets("NewCycle").Activate
srcWorksheet.Rows("1:1").Delete
If you are in Excel VBA, this isn't quite what you want. This code was written for an external app (say written in VB6) to open Excel remotely and then do stuff to that copy of Excel. If you are already in Excel/VBA you obviously don't need to do that.
In VBA, the equivalent code would be something like this:
Public Sub MyCode()
Dim wb as Workbook
Dim ws as Worksheet
Set wb = Application.Workbooks.Open("X:\GCIXCycleCompare_test_auto.xlsx")
Set ws = wb.Worksheets("NewCycle")
ws.Rows(1).Delete
End Sub
If you run this code (by click F5 from inside VBA ... or by run macro in Excel) it should open up the test file off the X: drive, and then delete the first row of it.

VBA: How to address the correct workbook when giving a worksheet as an argument to a function?

I have a question regarding the correct address of Workbooks in VBA, which I am fairly new to.
Here is what I have done so far:
I have written a sub that, amongst other things, creates a worksheet with the CodeName "table10".
Then I defined a function to manipulate the contents of said sheet: this function
Text_To_Numbers(worksheet as worksheet)
expects a worksheet argument. I call the function from another sub using the following line:
Call Text_To_Numbers(table10)
Now, here is my issue:
The above works flawlessly when the only open workbook is the one I want to manipulate with my function. However, when I have multiple open workbooks, the function will try to manipulate a different workbook, resulting in an error.
I am quite certain that there must be a way to specify the workbook to be used, but I am unable to find it. That being said, there is another complication: The name of the workbook which I would like to manipulate is machine generated, so it always has a different name. This means that using an explicit reference to the same file name time and again is not an option.
Could anybody help me resolve this?
You need to fully qualify objects in VBA to avoid situations like this where it is ambiguous what the parent is.
In your situation, you want the sheet to be connected to its parent workbook, so make sure you specify that it came from a given workbook!
You cannot directly refer to worksheets in other workbooks by their CodeName, this can only be done to the ThisWorkbook object (the workbook containing the VBA code). See the question Fully reference a worksheet by codename for details on how to get the sheet by its codename from another workbook. I have included the function in the answer and how to use it in this context.
You created the sheet table10 in one of the following:
ActiveWorkbook
ThisWorkbook
WB (some workbook object)
So you can access it using that workbook object without a need for the name!
Using ThisWorkbook.table10 should give same behaviour as just table10, but here are two neater examples for calling the function.
' A neater way to call the function:
Text_To_Numbers worksheet:=ThisWorkbook.table10
' You could also call it simply using
Text_To_Numbers ThisWorkbook.table10
If your sheet is not within ThisWorkbook
' Get sheet (from the workbook object you are using, WB) and pass to your Text_To_Numbers
Text_To_Numbers GetSheetWithCodename("table10", WB)
Function GetSheetWithCodename(ByVal worksheetCodename As String, Optional wb As Workbook) As Worksheet
Dim iSheet As Long
If wb Is Nothing Then Set wb = ThisWorkbook ' mimics the default behaviour
For iSheet = 1 To wb.Worksheets.Count
If wb.Worksheets(iSheet).CodeName = worksheetCodename Then
Set GetSheetWithCodename = wb.Worksheets(iSheet)
Exit Function
End If
Next iSheet
End Function
Try assigning the workbook and sheet to a variable then calling it in this way when you need to do some work in it:
Dim WB As Workbook
Dim WS As Worksheet
'If you want to open the workbook before doing work
Set WB = Workbooks.Open("/Workbook path name goes here”)
Set WS = WB.Worksheets("Table‌​10")
Then you just need to pass a call to the WS variable from within your function to perform operations within the specified sheet.
Edit:
Apologies, didn't realise you were trying to reference the index name in the project editor when I first read your question. The code name can be referenced from an external workbook with the following example which shows how to select the workbook and sheet codename to perform a copy/paste from one workbook to another:
Sub UseCodeNameFromOutsideProject()
Dim WS As Worksheet
With Workbooks("MyWorkbook.xlsb")
Set WS = _
.Worksheets(CStr(.VBProject.VBComponents("Sheet1").Properties(7)))
WS.Range("A1").Copy
Selection.Copy
WS.Range("B1").PasteSpecial
End With
End Sub
Thanks to Enderland for the idea.

Excel 2013 VBA: Setting activeworkbook when clicking between workbooks

I have a workbook with a userform that contains a listbox that is used to populate data on a sheet.
If I have multiple workbooks open and I click from one workbook directly to the listbox on the userform in the other workbook, the ListBox_Change event fires before Activeworkbook changes to reflect the workbook that contains the userform. So when the code reaches Set EqDataSht = ActiveWorkbook.Worksheets("Equipment-Data") I get a subscript out of range error because the workbook I'm coming from doesn't contain a sheet named "Equipment-Data".
What is the best way to set the ActiveWorkbook to the parent of the userform? Thoughts I've had are setting a public variable wb = ActiveWorkbook on workbook_open or just trapping Err.Number=9 and telling the user to click on the sheet before clicking the userform. I'm sure there is something simple I am completely overlooking (VBA amateur).
Thoughts?
Instead of activeworkbook use thisworkbook which returns the workbook in which the code resides.
To make it active thisworkbook.activate should work

Reference Excel Workbook made by Worksheet.copy Method

I am trying to write a macro to copy worksheets into a new Workbooks using the .Copy(MSDN) method and then save and email these newly created files out.
To do this I will need a reference to the newly created worksheet in my macro. I haven't found a way to do it directly with the copy and am hesitant to always look for Book1.xlsx.
Is there a way to grab the most recently opened workbook or easily compare before and after collections of workbooks?
You can tell the worksheet Copy method to place the sheet Before/After a sheet in another workbook. So create a new workbook and then copy your sheet to before the first sheet in the new workbook.
Dim newBook As Workbook
Set newBook = Workbooks.Add
Workbooks("source_book.xlsx").Worksheets("sheet_name").Copy Before:=newBook.Worksheets(1)
You've then got a valid workbook reference to the book that holds the copy of the sheet.
Oh alright then.
Dim origBook As Workbook, newBook As Workbook
Set origBook = Workbooks.ActiveWorkBook
yourcode..yourcode..yourcode.Copy
Set newBook = Workbooks.ActiveWorkBook
Something like that.