Selecting activeworksheet only when it exists in the workbook - vba

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

Related

Excel macro modification ( or maybe VBA ) to update the last included worksheet

Situation
Trying to copy a range of cells that include formulas from worksheet called "Sheet1" to the rest of other worksheets I found that I could do it performing "Fill Across Worksheets". It worked fine, so my next step was to record a Macro for it to be more efficient and worked just fine too.
The Problem
The problem is that when I include a new worksheet and run the Macro, the Macro does not consider the new worksheet so this last worksheet doesn't get updated.
I am including below the code created by the macro. In it I can see that it's including only the worksheets I have now in the workbook, so this is where I need help.
( My excel is in Spanish so when you read Ctrl+Mayus+Q, Mayus means Shiftkey )
Help
What I need is a way to modify this Macro so when it runs it will check and update all worksheets. Or, maybe it's because a Macro can't do this I may need a VBA code ? If this VBA is the way to resolve it, can you help me here with this ?
I appreciate all help
Thank you
Javier
Sub Macro2()
'
' Macro2 Macro
'
' Acceso directo: Ctrl+Mayús+Q
'
Range("A5:D12").Select
Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")).Select
Sheets("Sheet1").Activate
ActiveWindow.SelectedSheets.FillAcrossSheets Range:=Selection,
Type:=xlAll
Sheets("Sheet1").Select
End Sub
This is a work around, concerning that you want all the worksheets to have the value of the first worksheet in range A5:D12:
Sub TestMe()
Dim ws As Worksheet
Dim selAddress As String
selAddress = "A5:D12"
For Each ws In Worksheets
'ws.Range(selAddress).Value2 = Worksheets(1).Range(selAddress).Value2
ws.Range(selAddress).Formula = Worksheets(1).Range(selAddress).Formula
Next ws
End Sub
See How to avoid using Select in Excel VBA.

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

VBA to work on all sheets

I tried many different sample codes before posting this, but I can't get any of them to work.
I need this to run not just in the active sheet but on all sheets in my file.
On Error Resume Next
Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Hope someone is able to help.
You need to loop over the sheets in the workbook and manipulate each one individually:
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Worksheets
sheet.Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Next
The solution of Alex K. is OK, only check if the sheet is empty or not, otherwise you will have an error with "SpecialCells" :
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Worksheets
If WorksheetFunction.CountA(sheet.Cells) <> 0 Then
sheet.Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End If
Next
End Sub

Writing loop statement for active workbook

First of all, don't laugh. And if you do, just do it quietly. I have no idea how to write looping Visual basic, but I took my best shot. I'm trying to learn VBA as best I can, by doing, and I just need a push in the right direction. The idea is I want to write a simple macro that looks at each worksheet, evaluates whether or not there is grouping in rows 19-43,if there is grouping, gets rid of the grouping, if there is not grouping, go to the next worksheet, and if there is no more worksheets, end the loop.
Here's my attempt which obviously did not work.
Dim V As Variant
V = ActiveWorksheet
For Each V In Workbook
Rows("a29:43").Select
Selection.Rows.Ungroup
Next
Now, I also have no idea what the qualification is to say something like if it is grouped, then this, if not grouped, then this. I would imagine it's something like grouping = true but I couldn't figure it out. I am VERY grateful to any who spare some time to look at this.
You need to define the collection that you want to iterate over, so in this case it would be the worksheets contained in the workbook:
Dim wbk As Workbook
Dim sht As WorkSheet
Set wbk = ActiveWorkbook
For Each sht In wbk.Worksheets
sht.Rows("a29:43").Select ' this may give you trouble. Possibly try sht.Range("a29:a43").Select?
Selection.Rows.Ungroup
Next
Set wbk = Nothing ' Clean up our objects. Just to be sure.
As an aside, I don't know if it needs mentioned but just in case, I'd recommend you avoid ever using single-character variable names.
Couple of things:
As per #pnuts, you're missing an 'A' in your target range. This can be critical.
Ungroup will fail if rows are not grouped. This works kind of like Autofilter.
Best practices would be to use Range--not Rows, and just use the Rows property of Range--when dealing with target cells, unless a different approach is necessary or justified.
Here's a not-so-different take. Note the clear and explicit declarations of each variable. Also, read the comments. They're not the best, but they can help you on your apparent quest to learn more VBA. ;)
Sub UngroupRanges()
Dim wBk As Workbook, wSht As Worksheet
Dim rTarget As Range
Set wBk = ThisWorkbook 'Let wBk be this workbook.
For Each wSht In wBk.Worksheets 'Read: for each sheet in this workbook's collection of worksheets.
Set rTarget = wSht.Range("A29:A43") 'Read: I'll be setting rTarget as my target cells.
On Error Resume Next 'Read: If I hit an error after this line, I'll just continue executing.
rTarget.Rows.Ungroup 'Read: For all rows in rTarget, I'll do an ungroup.
On Error GoTo 0 'Read: If I hit an error after this, I won't skip anymore.
Next wSht 'Read: Move on to next worksheet.
Set wBk = Nothing 'Read: Release the assignment of this workbook to wBk.
End Sub
Let us know if this helps.

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