Activate an excel sheet from VBA without knowing it's name? - vba

Is it possible to activate a sheet in an opened workbook through VBA without knowing it's name? I'm opening a workbook using application.getfileopenname and reading data from it, but some of the workbooks have the data on the second sheet, instead of the first. Is there anyway I could switch the active worksheet to the second sheet?

Dim wsData As Worksheet
Set wsData = Sheets(1)
'If the Range doesn't have the value you are looking for switch sheets
If wsData.Range("A1").Value <> "MyExpectedData" Then Set wsData = Sheets(2)

Related

Copy and combine sheets to a workbook

I need VBA code for Excel which: will be activated by a button in an empty workbook, loop through open workbooks, copies only sheets called "specificsheetname" from workbooks and pastes it into a new worksheet in the button activator workbook. So idea is that it will combine many worksheets from different workbooks into a one workbook. I tried this:
Sub workbookFetcher()
Dim book As Workbook, sheet, wsNew, wsCurr As Worksheet
Set wsCurr = ActiveSheet
For Each book In Workbooks
For Each sheet In book.Worksheets
If sheet.Name = "COOLING_RAW" Then
Set wsNew = Sheets.Add(After:=wsCurr)
book.Worksheets("COOLING_RAW").Copy
Set wsNew = book.Worksheets("COOLING_RAW")
End If
Next sheet
Next book
End Sub
It kind of works but it pastes all the copied worksheets to a new workbook. That's not what I want, I want them to pasted in the same workbook.
As I said in my comment:
Sub workbookFetcher()
Dim book As Workbook, sheet as Worksheet
For Each book In Workbooks
For Each sheet In book.Worksheets
If sheet.Name = "COOLING_RAW" Then
book.Worksheets("COOLING_RAW").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
End If
Next sheet
Next book
End Sub
If you want it to be after the ActiveSheet and the ActiveSheet is in the middle of other sheets, you can still use your wsCurr and just increment the index.
If you've got Excel 2016, then the newly bundled PowerQuery functionality under the Get & Transform part of the ribbon is by far the best way to do this. Suggest you google something like PowerQuery Combine Workbooks and you'll see heaps of great tutorials showing you exactly what to do. It pretty much makes lots of VBA redundant, and it is childs-play to learn compared to VBA.
If you've got any other version of Excel from 2010 up and have admin rights on your machine, you can download and install PowerQuery from Microsoft's site...it's a free add-in
you don't need to iterate through each single workbook worksheets, while you just try to get the wanted sheet and copy it if it actually exists
moreover you want to avoid searching ThisWorkbook itsel for wanted worksheet, too!
Option Explicit
Sub workbookFetcher()
Dim book As Workbook, sht As Worksheet
For Each book In Workbooks
If book.Name <> ThisWorkbook.Name Then ' skip ThisWorkbook and avoid possible worksheet duplication
If GetWorksheet(book, "COOLING_RAW", sht) Then sht.Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count) ' if currently searched workbook has wanted worksheet then copy it to ThisWorkbook
End If
Next
End Sub
Function GetWorksheet(book As Workbook, shtName As String, sht As Worksheet) As Boolean
On Error Resume Next ' prevent subsequent statement possible error from stoping the function
Set sht = book.Worksheets(shtName) ' try getting the wanted sheet in the passed workbook
GetWorksheet = Not sht Is Nothing ' return 'True' if successfully got your sheet in the passed workbook
End Function

when executing macros/vba how can they be applied on merged cells?

I have the following question: A member from this forum yesterday provided a very good solution to my problem. I have two similar excel workbooks with more than 100 sheets in each, with the same sheet names. I wanted VBA to copy the data from sheet A in workbook A to sheet B in workbook B.
Sub GetDate()
Dim workbookA As Workbook, workbookB As Workbook, sheetA As Worksheet, sheetB As Worksheet, ws As Worksheet, sheetName As String
Set workbookA = Workbooks("clients.xls")
Set workbookB = Workbooks("KYC.xls")
'Loop through each worksheet in Book A
For Each ws In workbookB.Worksheets
Set sheetA = workbookA.Worksheets(ws.Name)
Set sheetB = workbookB.Worksheets(ws.Name)
sheetA.Range("C5").Copy sheetB.Range("E31")
Next
End Sub
I want to use it agan to get another values from another cell and insert it on workbookB on the approprate sheet each time. The problem is that on workbook A the cell I want to copy is a merged cell and so is the destination cell. I tried to give a name to each of the merged cells but I can't seem to make it. Can someone help if it can be solved?
thank you
Try
sheetA.Range("C5").MergeArea.Copy ' copies the merged cells that include C5
sheetB.Range("E31").PasteSpecial ' pastes what was copied into E31 and any merged cells it is part of

Copy appended data to a different worksheet

I have the following which is working in the same workbook how do I get this to use a summary sheet in a different workbook?
Sub SummurizeSheets()
Dim ws As Worksheet
Application.ScreenUpdating = False
Sheets("Summary").Activate
For Each ws In Worksheets
If ws.Name <> "Summary" Then
ws.Range("D2:D6, D8:D15").Copy
Worksheets("Summary").Cells(Rows.Count, 4).End(xlUp).PasteSpecial (xlPasteValues)
End If
Next ws
End Sub
Make sure you place the sub-routine in a Module, and not in
ThisWorkbook. You can insert a new module by right-clicking on workbook name (from the VBA editor) and going to Insert > Module.
Make sure the workbooks you want to use/reference are open.
Make sure the workbooks are all located in the same workbook collection. This is not a problem unless you manually create an additional instance of Excel.
Reference the workbooks using the Workbooks() object just like you
do with Worksheets.
Sub test()
Dim b2 As Workbook 'We will use this variable as a reference to the external workbook that contains the "Summary" worksheet.
Set b2 = Excel.Workbooks("testbook2") 'We assign the external workbook (which I named "testbook2" for the purposes of this example) to our 'b2' variable.
Dim ws1 As Worksheet
Dim ws2 As Worksheet 'We will use these variables as references to the worksheets we're using.
Set ws1 = Excel.ActiveSheet 'We set ws1 to equal our current sheet (which presumably is where you'll be copying data from).
Set ws2 = b2.Worksheets("Summary") 'We set ws2 to equal the sheet (named "Summary") in the external workbook (named "testbook2").
ws1.Range("D2:D6").Copy 'We copy the data from the active sheet, which we reference using our 'ws1' variable.
'Note: I had issues with using multiple ranges in the same object so I removed this from your code.
ws2.Cells(Rows.Count, 4).End(xlUp).PasteSpecial xlPasteValues 'You only need to use the ws2 variable since we've already defined it as the "Summary" sheet you want.
End Sub
I'm not sure why I follow that first rule, but I seem to remember having issues when using ThisWorkbook in conjunction with external workbook references.
Update
I edited the code to show you a better example of how to do this. You almost never need to use "Activate" or "Select" commands in VBA. Just assign variables and reference the values directly.

VBA: Copying a cell range to different workbook

I am currently working on an integrated set of workbooks, where I need to transfer data values between workbooks. In order to do so I need a VBA Macro that can copy a specific range (a row in a worksheet) and insert it at the bottom of an overview list in a different book.
How can I do this?
I am somewhat of a VBA novice, so specific instructions are appreciated.
Note: I'm using MS Excel 2010.
Thank you in advance!
The following example copy will copy the contents of the cells A1:A3 from a Worksheet named Source in a Workbook named workbook1.xlsx into the Worksheet named Target in a different Workbook, workbook1.xlsx. It will throw an error if either of the two Workbooks are not open, or if they do not contain the Worksheets that the Sub calls for.
Sub Example()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb1 = Workbooks("workbook1.xlsx")
Set wb2 = Workbooks("workbook2.xlsx")
Set ws1 = wb1.Sheets("Source")
Set ws2 = wb2.Sheets("Target")
ws2.Range("A1:A3") = ws1.Range("A1:A3").Value
End Sub

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