How to delete worksheets with specific names only - excel

My Master Report in fold.xlsm has a range of file and corresponding worksheets with tab names that correspond to the client and the type of data on that tab (indicated by variables xWs_Tax, xWs_Ins, etc.)
After storing these it then opens the corresponding client workbook.(replaced with fname.xlsx below)
The code is supposed to delete all worksheets NOT matching these stored names that include the client number in them. But I can't seem to get it to work. Either it deletes all the tabs or it does nothing at all depending on how I fiddle with it. Does anything jump out at you below or am I using bad code maybe? Do I need to do more then just declare Dim xWs As Worksheet ?
Here is where the variables are stored:
Dim xWs_ins As String
Dim xWs_tax As String
Dim xWs_ucc As String
Dim xWs_loc As String
Dim rc As String
rc = Range("P40")
For i = 41 To (rc + 40)
Workbooks("Master Report in fold.xlsm").Activate
MsgBox$ Range("J" & i)
xWs_ins = Range("J" & i)
xWs_tax = Range("K" & i)
xWs_ucc = Range("L" & i)
xWs_loc = Range("M" & i)
Workbooks.Open filename:= for example "20 Investor Certification - Master Servicers.xlsx
Dim xWs As Worksheet
''   Application.ScreenUpdating = False
'' Application.DisplayAlerts = False
For Each xWs In Application.ActiveWorkbook
If xWs.Name <> xWs_ins And xWs.Name <> xWs_tax And xWs.Name <> xWs_ucc And xWs.Name <> xWs_loc Then
xWs.Delete
End If
Next
'' Application.DisplayAlerts = True
'' Application.ScreenUpdating = True
ActiveWorkbook.Save
Next i

Delete Unwanted Sheets
There are unclear 'items' addressed in OP's comments and marked with ??? in the code.
Option Explicit
Sub deleteUnwanted()
Dim swb As Workbook: Set swb = Workbooks("Master Report in fold.xlsm")
' The worksheet name is unknown??? ("Sheet1")
Dim sws As Worksheet: sws = swb.Worksheets("Sheet1")
Dim sCell As Range
Dim srg As Range
Dim dwb As Workbook
Dim dsh As Object ' There is no 'Sheet' object.
Dim dArr As Variant
Dim dshCount As Long
' The workbook and worksheet are unknown??? (sws)
Dim rc As String: rc = sws.Range("P40").Value
Application.ScreenUpdating = False
For i = 41 To (rc + 40)
n = 0
Set sCell = sws.Cells(i, "I")
Set dwb = Workbooks.Open(sCell.Value)
dshCount = dwb.Sheets.Count
ReDim dArr(1 To dshCount)
Set srg = sws.Columns("J:M").Rows(i)
For Each dsh In dwb.Sheets
If IsError(Application.Match(dsh.Name, srg, 0)) Then
n = n + 1
dArr(n) = dsh.Name
End If
Next
If n > 0 Then
ReDim Preserve dArr(1 To n)
Application.DisplayAlerts = False
dwb.Worksheets(dArr).Delete
Application.DisplayAlerts = True
End If
dwb.Close SaveChanges:=True
Next i
Application.ScreenUpdating = True
End Sub

Related

VBA copy and past data from specific cells from multiple workbooks to master workbook (but need to copy the cell even if it is empty)

i need to make the bellow code copy even blank cell (to avoid input data from 2 workbooks in the same row), because the final output is going to be storing the data from each workbook to a single row .
`
Sub Copy_specific_Cells_From_other_workbooks_auto_RF()
Dim FileName$, sPath$
Dim wkbDest As Workbook, wkbSource As Workbook
Dim wsDest As Worksheet, wsSource As Worksheet
Application.ScreenUpdating = False
sPath = "D:\TSSRs\PO11\TSS Reports\WL TSSR\"
'sPath = "C:\Users\user\Documents\HP Laptop\Documents\Documents\Jobs\DIT\IDMB\Stack Overflow\okinawa\"
Set wkbDest = ThisWorkbook
'setting worksheet to improve readability
Set wsDest = wkbDest.Sheets("Master")
FileName = Dir(sPath)
Do While Len(FileName) > 0
'open workbook for read only
Set wkbSource = Workbooks.Open(sPath & FileName)
'setting worksheet to improve readability
Set wsSource = wkbSource.Sheets(2)
wsSource.Range("B2").Copy
wsDest.Cells(wsDest.Rows.Count, "I").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
wsSource.Range("B4").Copy
wsDest.Cells(wsDest.Rows.Count, "J").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
wsSource.Range("B6").Copy
wsDest.Cells(wsDest.Rows.Count, "K").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
wsSource.Range("B7").Copy
wsDest.Cells(wsDest.Rows.Count, "L").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
'not needed since we're closing the workbook; so it will be done automatically
'Application.CutCopyMode = False
wkbSource.Close SaveChanges:=False
FileName = Dir
Loop
Application.ScreenUpdating = True
End Sub
`
Copy to Rows in Another Workbook
Determine the last destination row (dRow) before the loop only once.
At the beginning of the loop, increment the destination row by one so it becomes the currently available row where all the values from the cells of the current source worksheet will be written to.
Sub RetrieveCellsData()
Const sFolderPath As String = "C:\Test\"
' The following two arrays need to have the same number of elements.
Dim sCells() As Variant: sCells = VBA.Array("B2", "B4", "B6", "B7")
Dim dColumns() As Variant: dColumns = VBA.Array("I", "J", "K", "L")
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Worksheets("Master")
' Determine the last destination row ('dRow').
Dim dRow As Long: dRow = dws.Cells(dws.Rows.Count, "I").End(xlUp).Row
' Pick another column if necessary or use another way, e.g.:
'With dws.UsedRange
' dRow = .Columns(1).Cells(.Rows.Count).Row
'End With
Dim sPath As String: sPath = sFolderPath
Dim pSep As String: pSep = Application.PathSeparator
If Right(sPath, 1) <> pSep Then sPath = sPath & pSep
Dim sFileName As String: sFileName = Dir(sPath)
If Len(sFileName) = 0 Then
MsgBox "No files found.", vbCritical
Exit Sub
End If
Dim nUpper As Long: nUpper = UBound(sCells) ' or UBound(dColumns)
Dim swb As Workbook
Dim sws As Worksheet
Dim sFilePath As String
Dim n As Long
Application.ScreenUpdating = False
Do While Len(sFileName) > 0
dRow = dRow + 1 ' All source cell values will be written to this row,
' whether they're empty or not i.e. don't 'xlUp' in the loop!
sFilePath = sPath & sFileName
Set swb = Workbooks.Open(sFilePath, , True) ' read-only
Set sws = swb.Sheets(2) ' pretty risky!
For n = 0 To nUpper
dws.Cells(dRow, dColumns(n)).Value = sws.Range(sCells(n)).Value
Next n
swb.Close SaveChanges:=False
sFileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Cells' data retrieved.", vbInformation
End Sub

Loop through drop down list and save the workbook as a new file

Hi I have the following code which loops through dropdown selections and saves each result as a new workbook based on the named range in cell G3. I am trying to edit the code so that it saves all the worksheets to the new file instead of just the active one, if anyone could help? thank you
Sub myFiles()
Dim wb As Workbook
Dim ws As Worksheet
Dim nwb As Workbook
Dim nws As Worksheet
Dim rng As Range
Dim Path As String
Dim myDate As String
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Summary")
Set rng = ws.Range("G3")
Path = "C:\Users\bradley\Desktop\Sales by Month\"
myDate = Format(Now(), "MM-DD-YYYY")
For i = 1 To 4
rng = ws.Range("J" & i)
ws.Copy
Set nwb = ActiveWorkbook
Set nws = nwb.Worksheets("Summary")
With nws
Cells.Copy
Cells.PasteSpecial (xlPasteValues)
End With
Application.DisplayAlerts = False
nwb.SaveAs FileName:=Path & rng & " " & myDate & ".xlsx",
FileFormat:=xlWorkbookDefault
nwb.Close
Application.DisplayAlerts = True
Next i
End Sub
Loop through the sheets but only create a workbook on the first one.
Option Explicit
Sub myFiles()
Const FOLDER = "C:\Users\bradley\Desktop\Sales by Month\"
Dim wb As Workbook, nwb As Workbook
Dim ws As Worksheet, rng As Range
Dim myDate As String, i As Long, j As Long
Dim filename As String
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Summary")
Set rng = ws.Range("G3")
myDate = Format(Now(), "MM-DD-YYYY")
Application.ScreenUpdating = False
For i = 1 To 4
rng.Value2 = ws.Range("J" & i).Value2
' copy all sheets
For j = 1 To wb.Sheets.Count
If j = 1 Then
wb.Sheets(j).Copy
Set nwb = ActiveWorkbook
Else
wb.Sheets(j).Copy after:=nwb.Sheets(j - 1)
End If
With nwb.Sheets(j)
.UsedRange.Value2 = .UsedRange.Value2
End With
Next
' save workbook
filename = FOLDER & rng.Value2 & " " & myDate & ".xlsx"
Application.DisplayAlerts = False
nwb.SaveAs filename:=filename, FileFormat:=xlWorkbookDefault
nwb.Close
Application.DisplayAlerts = True
Next i
Application.ScreenUpdating = True
MsgBox "Done"
End Sub

Struggling to copy between workbooks

I've got to copy one cell at a time to rearrange the columns from a specific row based on a value in that row. This code worked perfectly copying from one sheet to another sheet within one workbook. Now I have tried to expand it to copy between workbooks. I cannot for the life of me get it to work. Any help would be appreciated. Ps) Some code removed to simplify
Dim bomWB As Workbook
Set bomWB = ThisWorkbook
strFullname = ("C:\Users\AlexA\Desktop\") & PartNo
Workbooks.Add.SaveAs Filename:=strFullname ', FileFormat:=xlcsv
Dim NewWB As Workbook
Set NewWB = ThisWorkbook
bomWB.Activate
Dim xRg As Range
Dim xCell As Range
Dim I As Long
Dim R As Long
Dim L As Long
I = Worksheets("Main BOM").UsedRange.Rows.Count
Set xRg = Worksheets("Main BOM").Range("H2:H" & I)
On Error Resume Next
'Application.ScreenUpdating = False
For L = 1 To xRg.Count
If CStr(xRg(L).Value) = "0" Then GoTo Skip
R = R + 1
Workbooks(bomWB).Worksheets("Main BOM").Range("H" & L + 1).Copy _
Destination:=Workbooks(NewWB).Worksheets("Sheet1").Range("A" & R + 1)
Skip:
Next
Dim bomWB As Workbook
Set bomWB = ThisWorkbook
strFullname = ("C:\Users\AlexA\Desktop\") & PartNo
Workbooks.Add
Dim NewWB As Workbook
Set NewWB = ActiveWorkbook
bomWB.Activate
Dim xRg As Range
Dim xCell As Range
Dim I As Long
Dim R As Long
Dim L As Long
I = Worksheets("Main BOM").UsedRange.Rows.Count
Set xRg = Worksheets("Main BOM").Range("H2:H" & I)
On Error Resume Next
'Application.ScreenUpdating = False
For L = 1 To xRg.Count
If CStr(xRg(L).Value) = "0" Then GoTo Skip
R = R + 1
bomWB.Worksheets("Main BOM").Range("H" & L + 1).Copy _
Destination:=NewWB.Worksheets("Sheet1").Range("A" & R + 1)
Skip:
Next
NewWB.SaveAs Filename:=strFullname, FileFormat:=xlCSV
NewWB.Close

Excel VBA Hyperlinking Values Type Mismatch Error

I'm new to VBA and trying to put together a macro to copy in data from another workbook and then hyperlink values on an existing sheet to the sheets i've copied in based on a string value in a cell. For the most part the script works however i'm getting a type mismatch error. Hoping someone can help identify what i'm doing wrong.
Sub CopyTitleDetailData()
'Copy all sheets from Key New Release Detail sheet, overrides existing sheets, copys in new sheets
Dim wb As Workbook, ws As Worksheet, wbTarget As Workbook, wsTarget As Worksheet
Application.ScreenUpdating = False
Set wb = ActiveWorkbook 'Main workbook
Dim pth As String
pth = wb.Path
Dim titleDetailPth As String
titleDetailPth = Left(pth, InStrRev(pth, "\") - 1)
Dim filePthName As String
filePthName = titleDetailPth & "\Files for Pre-Order Report (Macro & Alteryx)\" & "Key New Release Accounts Details.xlsx"
Set wbTarget = Workbooks.Open(filePthName, UpdateLinks = False, ReadOnly = True)
For Each wsTarget In wbTarget.Worksheets 'A loop for each worksheet in the Key New Release Detail workbook
For Each ws In wb.Worksheets 'A loop for each worksheet in the Pre-Order (i.e. active workbook)
If wsTarget.Name = ws.Name Then 'If the sheet I am importing exists, it will be deleted
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wsTarget.Copy After:=wb.Sheets(wb.Sheets.Count) 'Copies it into the last sheet
wb.Sheets(wsTarget.Name).Visible = 0 'Hides the copied sheets
Next wsTarget
wbTarget.Close SaveChanges:=False
Application.ScreenUpdating = True
'Loops through a specified column and when a specified value is found, puts a hyperlink in the cell below
Const cWsName As String = "Title Detail"
Const cSearch As String = "Title"
Const cRow1 As Integer = 1
Const cRow2 As Integer = 800
Const cCol As String = "D"
Dim oWb As Workbook
Dim oWs As Worksheet
Dim rCell1 As Range
Dim rCell2 As Range
Dim iR As Integer
Dim strText As String
Dim strAddr As String
Set oWb = ActiveWorkbook
Set oWs = oWb.Worksheets(cWsName)
For iR = cRow1 To cRow2
Set rCell1 = oWs.Range(cCol & iR)
Set rCell2 = oWs.Range(cCol & iR + 1)
strText = rCell2.Text 'What's written in the cell.
strAddr = rCell2.Address 'The address e.g. B1, B13 ...
If rCell1 = cSearch Then
If strText <> "" Then
'Anchor is the place where i'm placing the hyperlink.
'SubAddress is where the hyperlink will take you
rCell2.Hyperlinks.Add _
Anchor:=rCell2, _
Address:="", _
SubAddress:="'" & rCell2 & "'!" & "A1", _
TextToDisplay:=strText 'The same text that orginally lived in the cell
Else
'What im doing if the cell is empty (i.e. nothing)
End If
End If
Next
Dim beginRow As Long
Dim endRow As Long
Dim chkCol As Long
Dim rowCnt As Long
Dim rngResult As Range
beginRow = 1
endRow = 800
chkCol = 1
With oWs
.Cells.EntireRow.Hidden = False 'Unhides all rows, remove line if that's not desired
For rowCnt = beginRow To endRow
If .Cells(rowCnt, chkCol) = "X" Then
If rngResult Is Nothing Then
Set rngResult = .Cells(rowCnt, 1)
Else
Set rngResult = Union(rngResult, .Cells(rowCnt, 1))
End If
End If
Next rowCnt
End With
If Not rngResult Is Nothing Then rngResult.EntireRow.Hidden = True
End Sub
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim oWs As Workbook
Dim targetString As String, targetSheet As Worksheet
Set oWs = ActiveWorkbook
targetString = Cells(Target.Range.Row, Target.Range.Column).Value
Set targetSheet = oWs.Sheets(targetString)
If targetSheet.Visible = False Then
targetSheet.Visible = True
End If
'End on Title Detail Sheet
targetSheet.Select
End Sub
Per this documentation, you have to provide an Address when adding a hyperlink. you seem to be setting Address = ""
https://learn.microsoft.com/en-us/office/vba/api/excel.hyperlinks.add

Split an excel file into multiple workbooks based on the contents of a column

I'm not experienced with VBA, but I think it's the only way for this to work.
I need to send a report to each sales team, but don't want to send them the information of other sales team. There are multiple sheets per workbook with different reports which all have a sales team column.
I would like all the sheets to be filtered by sales team, and create a new workbook for each team.
I appreciate any help.
I got this solution.
Just send me an email if you need this solution.
At first I got this format:
I create the following macro code
Option Explicit
Dim MainWorkBook As Workbook
Dim NewWorkBook As Workbook
Sub ExportWorksheet()
Dim Pointer As Long
Set MainWorkBook = ActiveWorkbook
Range("E2").Value = MainWorkBook.Sheets.Count
Application.ScreenUpdating = False 'enhance the performance
For Pointer = 2 To MainWorkBook.Sheets.Count
Set NewWorkBook = Workbooks.Add
MainWorkBook.Sheets(Pointer).Copy After:=NewWorkBook.Sheets(1)
Application.DisplayAlerts = False
NewWorkBook.Sheets(1).Delete
Application.DisplayAlerts = True
With NewWorkBook
.SaveAs Filename:="C:\Users\lengkgan\Desktop\Testing\" & MainWorkBook.Sheets(Pointer).Name & ".xls" 'you may change to yours
End With
NewWorkBook.Close SaveChanges:=True
Next Pointer
Application.ScreenUpdating = True
Range("D5").Value = "Export Completed"
End Sub
Following is the output
I have written a VBA(Macro) program which will work based on Input data. All you need to do is, provide input data in a column in another sheet. Macro will read the data and filter Master Sheet based on each row then it Generate new excel sheet based on find data.
enter Option Explicit
Dim personRows As Range 'Stores all of the rows found
'Split data into separate columns baed on the names defined in
'a RepList on the 'Names' sheet.
Sub SplitSalesData()
Dim wb As Workbook
Dim p As Range
Dim counter2 As Integer
Dim i As Integer
counter2 = 0
i = 0
Application.ScreenUpdating = False
' in my case i am generating new excel based on every 8 reacords from begining. You can simplyfy this logic based on your need.
For Each p In Sheets("Names").Range("RepList") ' Give the name of your input sheet and column
If i = 0 Then ' We are starting, so generate new excel in memeory.
Workbooks.Add
Set wb = ActiveWorkbook
ThisWorkbook.Activate
End If
WritePersonToWorkbook wb, p.Value
i = i + 1 ' Increment the counter reach time
If i = 8 Then ' As my need is after processing every 8 uniqe record just save the excel sheet and reset the processing
counter2 = counter2 + 1
wb.SaveAs ThisWorkbook.Path & "\salesdata_" & CStr(counter2) ' save the data at current directory location.
wb.Close
Set personRows = Nothing ' Once the process has completed for curent excelsheet, set the personRows as NULL
i = 0
End If
Next p
Application.ScreenUpdating = True
Set wb = Nothing
End Sub
'Writes all the data rows belonging to a RepList
Sub WritePersonToWorkbook(ByVal SalesWB As Workbook, _
ByVal Person As String)
Dim rw As Range
Dim firstRW As Range
For Each rw In UsedRange.Rows
If Not Not firstRW Is Nothing And Not IsNull(rw) Then
Set firstRW = rw ' WE want to add first row in each excel sheet.
End If
If Person = rw.Cells(1, 5) Then ' My filter is working based on "FeederID"
If personRows Is Nothing Then
Set personRows = firstRW
Set personRows = Union(personRows, rw)
Else
Set personRows = Union(personRows, rw)
End If
End If
Next rw
personRows.Copy SalesWB.Sheets(1).Cells(1, 1) ' Adding data in Excel sheet.
End Sub
please find below code
Sub SplitSheetDataIntoMultipleWorkbooksBasedOnSpecificColumn()
Dim objWorksheet As Excel.Worksheet
Dim nLastRow, nRow, nNextRow As Integer
Dim strColumnValue As String
Dim objDictionary As Object
Dim varColumnValues As Variant
Dim varColumnValue As Variant
Dim objExcelWorkbook As Excel.Workbook
Dim objSheet As Excel.Worksheet
Dim icol As Long
Dim l As Long
Dim headercol As Long
Dim stroutputfolder As String
stroutputfolder = "D:\Ba"
'dim str
icol = 1
headercol = 3
Set objWorksheet = ActiveSheet
nLastRow = objWorksheet.Range("A" & objWorksheet.Rows.Count).End(xlUp).Row
Set objDictionary = CreateObject("Scripting.Dictionary")
For nRow = headercol + 1 To nLastRow
'Get the specific Column
'Here my instance is "B" column
'You can change it to your case
strColumnValue = objWorksheet.Cells(nRow, icol).Value
If objDictionary.Exists(strColumnValue) = False Then
objDictionary.Add strColumnValue, 1
End If
Next
varColumnValues = objDictionary.Keys
For i = LBound(varColumnValues) To UBound(varColumnValues)
varColumnValue = varColumnValues(i)
'MsgBox (varColumnValues(i))
If Dir(stroutputfolder, vbDirectory) = vbNullString Then MkDir stroutputfolder
If CStr(varColumnValue) <> "" Then
objWorksheet.UsedRange.Offset(headercol - 1, 0).AutoFilter Field:=icol, Criteria1:=CStr(varColumnValue)
Set objExcelWorkbook = Excel.Application.Workbooks.Add
Set objSheet = objExcelWorkbook.Sheets(1)
objSheet.Name = objWorksheet.Name
objWorksheet.UsedRange.SpecialCells(xlCellTypeVisible).Copy Destination:=[A1]
'strFilename = strOutputFolder & "\" & strItem
ActiveWorkbook.SaveAs Filename:=stroutputfolder & "\" & CStr(varColumnValue) & ".xlsb", FileFormat:=50
ActiveWorkbook.Close savechanges:=False
l = l + 1
End If
Next
objWorksheet.ShowAllData
MsgBox (l & " files splitted")
End Sub

Resources