Activating Workbooks written a cell - vba

I'm working on an app that has to use two more excel files for its function. Names of those files change every day so I decided that both of those files are going to be opened from cells that contain functions to change the name based on the date like this.
Workbooks.Open Range("C2")
Windows("App.xlsm").Activate
Workbooks.Open Range("C16")
Now the problem is that I don't know how to switch between the books that I've opened. Normally I'd use something like this:
Windows("A.xlsx").Activate
But I clearly can't do that now. My idea was to activate App.xlsm and then activate a workbook written in the cell that I used like his:
Windows(Workbooks("App.xlsm").Sheets("Pom").Range("C16").Value).Activate
However that doesn't work. Now I'm not sure whether my code is wrong or whether this method just isn't possible. Can someone help me please ?

Use variables to have a handle on the workbooks
Dim wb1 as workbook
dim wb2 as workbook
set wb1 = Workbooks.Open (Range("C2"))
set wb2 = Workbooks.Open (Range("C16"))
' Activate wb1
wb1.activate
' or activate wb2
wb2.activate

Related

Tranfser data between two closed workbooks without creating a new one

how do I tranfser data between two closed workbooks without creating a new one? I have the following scenario:
2 excel workbooks(wb1 and wb2) with different structures
I need certain data from wb1 to be transfered to wb2
I can't modify wb1 & wb2 with macros
My question: Is it possible to activate a macro from a seperate excel workbook - lets name it wb3? So, triggering the macro in wb3 would transfer all the relevant data from wb1 to wb2....how would a macro like this look like?
Thanks!
Sub CommandButton1_Click()
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = Application.workbooks.open("C:\Users\PlutoX\MyExcelfile1.xlsx")
Set wb2 = Application.workbooks.open("C:\Users\PlutoX\MyExcelfile1.xlsx")
wb2.Sheets("Sheet1").Range("A1") = wb1.Sheets("Sheet1").Range("A1")
wb1.Close False
wb2.Close True
End Sub
Almost there! You need to change three things:
If you want to open a workbook, you need to state the full path
Set wb1 = Application.workbooks.open("C:\Users\PlutoX\MyExcelfile1.xlsx")
If stuff needs to be transferred to wb2, the order is wb2 = wb1 so
wb2.sheets("Sheet1").Range("A1").value = wb1.sheets("Sheet1").Range("A1").value
If you close the workbooks, make sure you save at least the one with changes
wb2.Close True

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.

Define a cell as a variable to be used in workbook reference

I am attempting to define a cell as a variable so that I can use it when calling upon a workbook. This cell changes daily and before running this macro I create a brand new workbook with this cell as the title.
This is what I have but obviously it won't work:
Dim wbk As Workbook
Set wbk = "X:\myname\TESTOCD\&"Sheets("MockupHelp").Range("d29")"""
The cell I am referencing that changes daily is in my sheet MockUpHelp is D29.
Try,
set wbk = workbooks.open("X:\myname\TESTOCD\" & Sheets("MockupHelp").Range("d29").value & ".xlsx")
Not sure if you need the .xlsx thrown on the tail end but that should give you the general idea.
An alternative method would be to declare your variable as a Name, using the Name Manager in the Formulas ribbon. Example: declare "MY_TEST_RANGE" to be equal to $D$29. When you refer to it in your code, you can refer directly to MY_TEST_RANGE, as you would any other variable.
This has the advantage of updating automatically whenever rows are inserted etc. within your workbook.
If you instead mean that people need to manually change the cell being referred to, there are other (similar) methods available let me know if that's the case.
Dim wbk As Workbook
Set wbk = Workbooks.Open("X:\myname\TESTOCD\" & _
Sheets("MockupHelp").Range("D29").Value)

Dealing with Run-time error '9': Subscript out of range when iterating over Worksheet

Not an Excel/VB expert but I keep getting
Run time error: 9: Subscript out of range
The error is occurring at the For Each line. Not sure why. I'm trying to copy worksheets from one workbook to another workbook.
The Workbook strFileName is being open successfully and the workbook does contain two other worksheets but code is failing on next line. I've seen similar posts regarding similar issue but have not had any luck. Any advice would be great. (I'm using Excel 2010) Thanks
Workbooks.Open (strFileName)
For Each sheet In Workbooks(strFileName).Worksheets
total = Workbooks(activeWKBook).Worksheets.Count
Workbooks(strFileName).Worksheets(sheet.Name).Copy _
after:=Workbooks(activeWKBook).Worksheets(total)
Next sheet
strFileName contains the full path of the workbook.
So you cannot use it in Workbooks(strFileName) since it only expects the workbook name.
This is how you should do it:
Dim wbName As String
wbName = Split(strFileName, "\")(Ubound(Split(strFileName, "\"))) ' Get the WB Name
For Each sheet In Workbooks(wbName).Worksheets
' Other cool stuff goes here
Next
But it is better to be explicit right away so you'll not have to worry about default path separator.
Remember that it is not always \. So I suggest you try below.
Dim myWB As Workbook
Set myWB = Workbooks.Open(strFileName)
Dim sheet As Worksheet
For Each sheet In myWB.Worksheets
With Thisworkbook ' Explicitly refer to the workbook that contains the code
sheet.Copy After:=.Sheets(.Sheets.Count)
End With
Next
Remember, you need to use ThisWorkbook in place of ActiveWorkbook.
Why? Because the moment you open the other workbook, the currently opened workbook becomes the ActiveWorkbook.
So to copy all sheets from the opened workbook to the workbook that contains the code, use ThisWorkbook instead.

How do I activate a specific workbook and a specific sheet?

How do I activate my Other workbook from the Current workbook? I have a current workbook with dumb.xls and The other workbook name as Tire.xls.I have opened the Tire.xls from the dumb.xls using worksbooks.open filename:= "name of the file".Its getting open but The problem is Im unable to make it work.
If I say cells(2,24).value=24 puts these value in the cell of dumb.xls but I want it to be done one Tire.xls.
activesheet.cells(2,24).value=24 puts these on Tire.xls. But how do i activate the Workbook with the name ? I need to open 3 to 4 excel workbooks And perform the operation? How do I activate the specific workbook
I have found this code on google
activeworkbook.worksheet("sheetname").activate ' but not working
windows("sheetname").activate ' people on google suggested not to use
Its not getting activated. I dont know how to make it work. Can anyone tell me How do i activate a specific workbook and a specific sheet of the other workbook ?
Example: I have niko.xls and niko_2.xls opened as workbooks from the dumb.xls workbook so totally 3 workbooks and I have to activate the 2nd sheet of niko_2.xls workbook.How do I make it? Can anyone explain me the syntax with these example? Thank you in advance
You do not need to activate the sheet (you'll take a huge performance hit for doing so, actually). Since you are declaring an object for the sheet, when you call the method starting with "wb." you are selecting that object. For example, you can jump in between workbooks without activating anything like here:
Sub Test()
Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test1.xls")
Dim wb2 As Excel.Workbook
Set wb2 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test2.xls")
wb1.Sheets("Sheet1").Cells(1, 1).Value = 24
wb2.Sheets("Sheet1").Cells(1, 1).Value = 24
wb1.Sheets("Sheet1").Cells(2, 1).Value = 54
End Sub
You have to set a reference to the workbook you're opening. Then you can do anything you want with that workbook by using its reference.
Dim wkb As Workbook
Set wkb = Workbooks.Open("Tire.xls") ' open workbook and set reference!
wkb.Sheets("Sheet1").Activate
wkb.Sheets("Sheet1").Cells(2, 1).Value = 123
Could even set a reference to the sheet, which will make life easier later:
Dim wkb As Workbook
Dim sht As Worksheet
Set wkb = Workbooks.Open("Tire.xls")
Set sht = wkb.Sheets("Sheet2")
sht.Activate
sht.Cells(2, 1) = 123
Others have pointed out that .Activate may be superfluous in your case. You don't strictly need to activate a sheet before editing its cells. But, if that's what you want to do, it does no harm to activate -- except for a small hit to performance which should not be noticeable as long as you do it only once or a few times. However, if you activate many times e.g. in a loop, it will slow things down significantly, so activate should be avoided.
You can try this.
Workbooks("Tire.xls").Activate
ThisWorkbook.Sheets("Sheet1").Select
Cells(2,24).value=24
The code that worked for me is:
ThisWorkbook.Sheets("sheetName").Activate
try this
Windows("name.xls").Activate
Dim Wb As Excel.Workbook
Set Wb = Workbooks.Open(file_path)
Wb.Sheets("Sheet1").Cells(2,24).Value = 24
Wb.Close
To know the sheets name to refer in Wb.Sheets("sheetname") you can use the following :
Dim sht as Worksheet
For Each sht In tempWB.Sheets
Debug.Print sht.Name
Next sht