Refer a particular sheet - vba

I want to search a particular Worksheet(Say "FebData") in all opened workbooks provided name of all workbooks totally depends on the user(it can be anything).To be honest by googling and putting some efforts form my side as well i got this code.
Dim wbSearch As Workbook, wsSearch As Worksheet, wsFind As Worksheet
Dim name As String
Dim j As String
name = InputBox("Enter your Sheet Name, You are searching for.")
If Len(name) = 0 Then 'Checking if Length of name is 0 characters
MsgBox "Please enter a valid name!", vbCritical
Else
j = name
End If
' to search a worksheet in all opened worksheets
For Each wbSearch In Application.Workbooks
For Each wsSearch In ActiveWorkbook.Sheets
if wsFInd = j then
worksheet("j").activate
else
Next wsSearch
Next wbSearch
end if
At last i want to add a feature which i don't have any idea about how to write a code for that, is if two worksheets of same name(Input from user) are present just pop up a msgbox "Duplicate sheet found".

This will loop through the workbooks and then loop through each sheet
Sub LoopBks()
Dim wb As Workbook, sh As Worksheet
For Each wb In Application.Workbooks
If wb.Name <> ActiveWorkbook.Name Then
For Each sh In wb.Sheets
If sh.Name = "FebData" Then
MsgBox "Sheets found in..." & wb.Name
End If
Next sh
End If
Next wb
End Sub

Related

When copy and pasting a range, the open workbook is selected incorrectly using a with statement in VBA

I am trying to copy the range from one worksheet and paste it into another workbook and then do the same for another range in a different workbook. The issue I am having is it is taking what seems to be taking the range from the "most recently opened" workbook rather than selecting the correct one.
See below the following code:
Sub CopyTEST()
Dim Wb1 As Workbook, wb2 As Workbook, wb3 As Workbook, wB As Workbook
Dim rngToCopy1 As Range, rngToCopy2 As Range
Dim wbName1 As String, wbName2 As String
wbName1 = "Book"
wbName2 = "APP"
For Each wB In Application.Workbooks
If wB.Name Like wbName2 & "*" Then
Set Wb1 = wB
Debug.Print Wb1.Name
End If
If wB.Name Like wbName1 & "*" Then
With wB.Sheets("Sheet1")
If Left(Right(Cells(6, 4), 4), 2) = "12" Then
MsgBox ("12")
Set wb2 = wB
ElseIf Left(Right(Cells(6, 4), 4), 2) = "10" Then
MsgBox ("10")
Set wb3 = wB
Set wb3 = wB
Else
MsgBox ("ERROR")
Exit Sub
End If
End With
End If
Next wB
With wb2.Sheets("Sheet1")
Set rngToCopy1 = .Range("A1:II82")
End With
With wb3.Sheets("Sheet1")
Set rngToCopy2 = .Range("A1:II82")
End With
With Wb1
.Sheets("A").Range("A1:II82").Value = rngToCopy2.Value
.Sheets("B").Range("A1:II82").Value = rngToCopy1.Value
End With
End Sub
The issue I am seeming to have is say we have Book3 where the cells are equal to 12 and then Book4 where the cells are equal to 10. If Book4 is directly open then when we are going through the For loop with each wB, and we are observing Book3, it will take the range from Book4 instead of Book3...
The If statements obvserving the cells in the worksheets are showing correct values when I step into the code, they are just selecting the wrong ranges...
I hope this makes sense... Thanks!
You are not carrying the parent reference you created on to the cells.
With wB.Sheets("Sheet1")
If .Cells(6, 4) = "12" Then
MsgBox ("12")
Set wb2 = wB
ElseIf .Cells(6, 4) = "10" Then
MsgBox ("10")
Set wb3 = wB
Else
MsgBox ("ERROR")
Exit Sub
End If
End With
Note .Cells not Cells. This transfers the workbook/worksheet from the With ... End With to .Cells.

Combine Worksheets Into New Workbook Based on Criteria and Save

I have a workbook made up with 100+ worksheets. These worksheets have account number/names/days in the name of the worksheet.
The naming convention for the worksheets follows this pattern of AccountNumber/AccountName/Description:
11-Greg-Monday
11-Greg-Tuesday
11-Greg-Friday
38-Rachel-Sunday
38-Rachel-Tuesday
38-Rachel-Saturday
I would like Excel to loop through all the worksheets, and extract all of the 11-Greg worksheets and save into a new workbook named 11-Greg, and then do the same for 38-Rachel, etc. I have a list of the account numbers/names on a worksheet named "Accounts" in the workbook.
Would it be possible to maintain the formulas after the extract of the worksheets, and formatting like column widths?
I found this code that might work to start, but I don't know how to reference the list on the "Accounts" tab to loop through for the account names?
Dim wb as Workbook, sht as WorkSheet
Dim strFileName As String
'Copy sheet as a new workbook
ActiveWorkbook.Sheets("Sheet1").Copy
Set wb = ActiveWorkbook
Set sht = wb.Sheets(1)
'SaveAs
strFileName = Application.GetSaveAsFilename(wb.Name) & "xlsx"
If strFileName = "False" Then Exit Sub 'User Canceled
wb.SaveAs Filename:=strFileName
The easiest way would be to create a list of the names you want to stack on a separate list. set that list as a range and then loop through each cell checking to see if the x letters of the sheet name match. something like this
Sub stacksheets()
Dim rng As Range, cCell As Range
Dim ws As Worksheet
Dim wb As Workbook, wb2 As Workbook
Dim shName As String
Set rng = ActiveWorkbook.Sheets("list").Range("a1:a2") ''this would be the list of names
Set wb2 = ActiveWorkbook ''remembering activeworkbook so can return
For Each cCell In rng
shName = Left(cCell.Value, 5) ''this needs to be the minimum letters from each name that is unique
Set wb = Workbooks.Add
For Each ws In wb2.Sheets
If InStr(ws.Name, shName) > 0 Then ''checks for name in sheet name
ws.Copy after:=wb.Sheets(1)
wb2.Activate
End If
Next ws
wb.SaveAs (wb2.Path & "\" & cCell.Value) '' saves workbook as list name
Next cCell
End Sub

VBA delete all worksheets in all workbooks that dont equal "summary details"

I cant seem to get the code to loop to the next workbook open. After that I would like to consolidate all the single worksheets in each workbook into a single workbook and rename each tab based on it's workbook name.
I am not too far but sentence one is my first task
Sub cullworkbooksandCONSOLIDATE()
Dim ws As Worksheet
Dim wb As Workbook
Dim wsNAME As String
For Each wb In Application.Workbooks
With wb
For Each ws In ActiveWorkbook.Worksheets
With ws
wsNAME = ws.Name
If wsNAME <> "summary details" Then
ws.Delete
End If
End With
Next
End With
Next
End Sub
thank you kindly
Or more directly, just copy the sheet if it exists, rather than deleting all the non matches (which will also cause an error if the code deletes all sheets)
Sub cullworkbooksandCONSOLIDATE()
Dim wb As Workbook
Dim wb1 As Workbook
Dim ws As Worksheet
Dim wsNAME As String
Set wb1 = Workbooks.Add(1)
wsNAME = "summary details"
For Each wb In Application.Workbooks
With wb
If .Name <> wb1.Name Then 'if it's not the export workbook
On Error Resume Next
Set ws = wb.Sheets(wsNAME)
On Error GoTo 0
If Not ws Is Nothing Then ws.Copy Before:=wb1.Sheets(1)
End If
End With
Next
End Sub
This is so not going into my resumé.
Sub cullworkbooksandCONSOLIDATE()
Dim ws As Worksheet
Dim wb As Workbook
Dim wsNAME As String
Dim wbex As Workbook
'You'll need to define wbex, this is where your worksheets will be inserted
For Each wb In Application.Workbooks
With wb
If .Name <> wbex.Name Then 'if it's not the export workbook
For Each ws In wb.Worksheets 'not necessarily active workbook
With ws
wsNAME = LCase(.Name)
If wsNAME <> "summary details" Then
.Delete 'why do you need to delete it?
Else
.Name = wb.Name
.Copy Before:=wbex.Sheets(1)
End If
End With
Next
.Close SaveChanges:=False 'you really don't want to corrupt your source data, do you?
End If
End With
Next
End Sub

Save Selected Sheets to a different work book in VBA

I would like to save a number of worksheets from the current workbook to a different workbook and exclude a sheet named "buttons" (in current one) from that saving process.
Can anybody help please? The number of worksheets is changeable FYI.
Below is what I have so far which include all the sheets from current workbook.
Sub SaveAs()
D1 = VBA.Format(Now, "mm_DD_yyyy")
For Each ws In Application.Workbooks
ws.SaveAs Filename:="C:\Users\e2309\Desktop\Andy's\GBB_Report_" & D1 & ".csv"
Next ws
Application.Quit
End Sub
Or more directly
copy the entire workbook
delete the redundant sheet
code
Sub Simpler()
Dim wb As Workbook
Dim strFile As String
strFile = "C:\temp\yourfile.xlsm"
ThisWorkbook.SaveAs strFile, xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = False
ThisWorkbook.Sheets("buttons").Delete
Application.DisplayAlerts = True
End Sub
This might get you a little closer. Note this is not complete and very untested.
Sub work()
Dim WB As Workbook
Dim Nwb As Workbook
Dim WS As Worksheet
Set Nwb = New Workbook
Set WB = ThisWorkbook
For Each WS In WB.Sheets
If WS.Name <> "Don't copy" Then
WS.Copy Nwb.Sheets("sheet1")
End If
Next
Nwb.Save
End Sub

VBA Copy/Paste from one Sheet to All Others

I am trying to copy one cell (D1) of sheet1 to a cell (D1) of all the workbook's other sheets (I am looping through files here and the number of worksheet varies).
When running the code below, the line "ActiveSheet.Paste" gives me the following error: "Run-time error '10004': Paste method of Worksheet class failed".
Here is the problematic piece of code:
'copy MSA code to sheets!=1
Sub MSAallSheets(wb As Workbook)
With wb
Range("D1").Copy
For Each ws In wb.Worksheets
If ws.Name <> "Page 1" Then
ws.Activate
ws.Range("D1").Select
ActiveSheet.Paste
End If
Next
End With
End Sub
In case it might be necessary, here is how I defined my loop through files:
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = "C:\Users\julia.anderson\Documents\HMDA\test\"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
DoWork wb
Delete wb
MSAallSheets wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub
Suggestions would be most welcome!
Thank you.
I'm guessing which sheet you're copying from...
Sub MSAallSheets(wb As Workbook)
With wb
Range("D1").Copy
For Each ws In wb.Worksheets
If ws.Name <> "Page 1" Then
wb.Sheets("Page 1").Range("D1").Copy _
ws.Range("D1")
End If
Next
End With
End Sub
This works for me with a slight alteration:
Sub MSAallSheets(wb As Workbook, SourceSheet As String, SourceAddress As String)
With wb
Sheets(SourceSheet).Range(SourceAddress).Copy
For Each ws In wb.Worksheets
If ws.Name <> SourceSheet Then
ws.Activate
ws.Range(SourceAddress).Select
ActiveSheet.Paste
End If
Next
End With
End Sub
example call:
call MSAallSheets(activeWorkbook, "Page 1", "D1")
The parameters make it easier to change minor details / reuse the code.