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

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

Related

Selecting activeworksheet only when it exists in the workbook

I have a VBA module where I want to select a worksheet, but only if it is present in the workbook.
So if I use activeworksheets code this gives an error if the worksheet is not in the workbook.
I have these for 3 worksheets, so I have tried if error but this only works if one of the worksheets is missing, as if error only handles the first case and cannot handle further cases.
Any suggestions?
There are many ways to solve this. My suggestion is doing
Dim ws as Worksheet
Set ws = Worksheets(1)
if ws.Name == "Worksheet I want"
'Do your thing
End if
Idk how many sheets you have. Use a for with Application.Sheets.Count if you need to.
Hope this helps

Activating Workbooks written a cell

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

Copying and pasting between workbooks

So I currently have three workbooks, I have created a folder in my Desktop, and where I am using workbook x, through a range on a cell to open up workbook called m (old) and workbook called n (new). I am then updating the old with the new.
Problem
Once I have opened up m, I am having to do a save as of the file as a newname. I am keen to know is there way of referring to it without using the workbook newname, as this workbook name would be concatenated with today's date and the name can be quite long and time consuming to type. I have produced several subroutines, one to remove protection etc,. and one for carrying out the coping actions and I am calling the subroutines, I just want to now if there is way of linking the newsaved name to some of the subroutines from referencing. Alternatively the old file could be saved at the very end. I am keen to pursue this avenue as I will be playing in certain other cases with four workbooks.
I have taken this code and amended it, but I am unable to open both spreadsheets, the strange thing when i block out the code and go through a test both work for each path they work, but not at the same time.
this is the code i amended, which i was able to find in
Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")
Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")
With ws1
.Cells.Copy ws2.cells
y.Close True
x.Close False
End With
End Sub
this is my code where it is not opening both workbooks
Dim wb as Workbook
Dim wb1 As Workbook, wb2 As Workbook
Dim ws as Worksheet, ws1 As Worksheet, ws2 As Worksheet
Dim Lst As Long,
Dim r1, r2 As Range
Set wb = ThisWorkbook
Set wb1 = Workbooks.Open("Sheets("x").Range("A4").Value")
Set wb2 = Workbooks.Open("Sheets("x").Range("A5").Value")
With wb2
Call Wbkunprtect()
I would be grateful for some help, please for those who are trigger happy can you hold back from pressing the down arrow some of us are not excel knowledgeable and also trying to learn and do not want to be banned from asking questions, I am trying to move data between two workbooks wb1 and wb2, through another wb i have completed my code, and this is the bit which stopping me from going forward.
I have learned a great deal from this site the reason I asked certain questions as I am reluctant to use select or activate as I have been told this is a bad habit you have to keep away from.
From what I understood, you'll need to use a WorkBook object! the WorkBook object will have the instance of the newly added workbook. It is as simple as that:
Sub example_new_workbook()
Dim wb As Workbook
Set wb = Workbooks.Add
wb.SaveAs ("path where you want to save")
End Sub
That way, "wb" will have the instance of the new workbook, and you can use freely to reference that new workbook. Remember, the WorkBooks object holds all the instances of all open workbooks, so you can get the reference for any other workbook through this object.
As to make it "Global", you can declare it outside the "Sub" scope, so the variable will be permanent as long as the module (or wherever you put your code) is open like this:
public wb as Workbook
Sub <your_routines>()
...
End Sub

How to access a closed Excel Workbook using vlookup vba

I'm trying to create a Excel VBA macro that uses VLOOKUP to access a range of cells in a closed workbook. I'm not too good at using the VBA editor, but it doesn't seem to show a lot of useful information about errors.
Sub WorkBookWithData()
Dim currentWb As Workbook
Set currentWb = ThisWorkbook
Dim currentWs As Worksheet
Set currentWs = currentWb.Sheets(1)
Dim strFormula As String
strFormula = "=VLOOKUP(currentWs.Range("B2"),'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
currentWs.Range("C2").Formula = strFormula
End Sub
Excel VBA editor is hanging up on the "strFormula = "=VLOOKUP..." section.
Thanks
Reference from Siddharth Rout's comments.
The main problem in your code is this line:
strFormula = "=VLOOKUP(currentWs.Range("B2"),'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
because of this code currentWs.Range("B2"). We know that you want to indicate Range("B2") of Current Sheet(same sheet). So, you can use as follow:
strFormula = "=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B‌​222,2,false)"
Why? It can use just B2 because you set formula to a cell which is in the same sheet. So, it is not need to indicate the Sheet Name.
And If you want to set a cell which is from other sheet, you need to indicate Sheet Name in that case. So, should use as follow:
strFormula = "=VLOOKUP(" & currentWs.name & "!B2,'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
This looks nothing like what I had previously, but it works.
Sub Check_Master_Values()
Dim newCurWb As Workbook
Set newCurWb = Workbooks(2)
newCurWb.Activate
newCurWb.Sheets(1).Range("C2").Formula = "=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:$B$269,2,FALSE)"
End Sub
In my first attempt, I didn't follow the chain of assignments from workbook, to sheets, to ranges. As you can see in this code, I Dim a new Workbook - then the big ah-ha moment, I needed to assign it to the correct open workbook. Then, I activated the workbook, and finally accessed the Sheets object and Range.
I also know now that my workbook selection number will vary depending on how many other workbooks are open. The ThisBook didn't work because somehow in the process, the workbook that ThisBook referenced, changed. That is probably also why my initial code didn't work, in addition to the improper coding in the VLOOKUP.
It would be good if there was a way to specify which workbook on the fly.
Thanks to everyone who gave help on the VLOOKUP part.

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.