Excel Checkbox Selected sheets to Another Worksheet - excel

I need help in making some changes to the existing VBA.
Based on the "Sheet" name and Sheet No., the existing code was used to copy a selected checkbox sheet to a new workbook.
I'd like to make it flexible so that the code still works when I rename or create a new sheet.
Private Sub ExportSheet_Click()
Dim wbNew As Workbook
Dim ws As Worksheet
Dim cnt As Control
Dim fileName As String
Const chBx As String = "CheckBox"
Application.ScreenUpdating = False
fileName = ThisWorkbook.Path & "\" & Me.Cmbteam.Value & ".xlsx"
Set wbNew = Workbooks.Add
Application.DisplayAlerts = False
Do Until wbNew.Worksheets.Count = 1
wbNew.Worksheets(2).Delete
Loop
Application.DisplayAlerts = True
Set ws = wbNew.Worksheets(1)
ws.Name = "DELETE_ME_LATER"
For Each cnt In Me.Controls
If Left(cnt.Name, Len(chBx)) = chBx Then
If cnt.Value = True Then
ThisWorkbook.Worksheets("Sheet" & Mid(cnt.Name, Len(chBx) + 1)).Copy after:=wbNew.Worksheets(wbNew.Worksheets.Count)
End If
End If
Next cnt
If wbNew.Worksheets.Count = 1 Then
MsgBox "No boxes were checked." & vbNewLine & "No file created", vbExclamation + vbOKOnly, "No selection made"
wbNew.Close savechanges:=False
Else
Application.DisplayAlerts = False
'Delete dummy sheet
ws.Delete
wbNew.Close savechanges:=True, Filename:=fileName
Application.DisplayAlerts = True
MsgBox "File saved at:" & vbNewLine & fileName
Unload Me
End If
Application.ScreenUpdating = True
End Sub

Related

Create another file but don't split worksheets into separate files

Separate worksheets into separate files
Hi I am using code
Sub Split_Sheet_into_ExcelFiles()
Dim FilePath As String
FilePath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each Sheet In ThisWorkbook.Sheets
Sheet.Copy
Application.ActiveWorkbook.SaveAs Filename:=FilePath & "\" & Sheet.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
It creates the same file but I was trying to split multiple worksheets into individual files. ANy idea what I'm typing wrong? Thanks
Export Each Sheet to an Individual File
Option Explicit
Sub ExportSheets()
Const PROC_TITLE As String = "Export Sheets"
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
Dim dFilePath As String: dFilePath = swb.Path
If Len(dFilePath) = 0 Then
MsgBox "The path cannot be determined." & vbLf & "Please save the " _
& "workbook before using this procedure.", vbCritical, PROC_TITLE
Exit Sub
End If
Application.ScreenUpdating = False
Dim dwb As Workbook, ssh As Object, sshCount As Long
For Each ssh In swb.Sheets
If ssh.Visible = xlSheetVisible Then ' sheet is visible
ssh.Copy
Set dwb = Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs Filename:=dFilePath & "\" & ssh.Name
Application.DisplayAlerts = False
dwb.Close SaveChanges:=False
sshCount = sshCount + 1
'Else ' sheet is not visible; do nothing!?
End If
Next ssh
Application.ScreenUpdating = True
MsgBox sshCount & " sheet" & IIf(sshCount = 1, "", "s") _
& " exported.", vbInformation, PROC_TITLE
End Sub

Save each worksheet with formatting in loop

I have a template file and 4 source documents that I use to fill the template. For each row in sheet2, I create a new blank template and fill it out, resulting in somewhere between 10-100 files. I want to save these in a loop, but having issues with Excel force closing on me. This is my code so far, recycled from a different project.
Dim w As Long, wb As Workbook
Dim fp As String, fn As String
Dim folderName As String
Dim fsoFSO
On Error GoTo bm_Safe_Exit
'Application.ScreenUpdating = False 'stop screen flashing
Application.DisplayAlerts = False 'stop confirmation alerts
'start with a reference to ThisWorkbook
With ThisWorkbook
folderName = Format(Date, "ddmmyyyy")
'set path to save
'fp = "<PATH HERE>" & folderName
fp = "C:\Users\Username\OneDrive - CompanyName\Documents\Projects\ThisProject\csvOutput\" & folderName
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
If fsoFSO.FolderExists(fp) Then
MsgBox "FOLDER - " & fp & " ALREADY EXISTS, DELETE CONTENTS TO PROCEED"
Exit Sub
Else
fsoFSO.CreateFolder (fp)
End If
'cycle through each of the worksheets
For w = 6 To Worksheets.Count
With Worksheets(w)
.Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
With ActiveWorkbook
fn = .Worksheets(1).Name
Cells.Select
Selection.SpecialCells(xlCellTypeVisible).Copy
Worksheets.Add after:=Sheets(Sheets.Count)
Range("A1").Select
ActiveSheet.Paste
Worksheets(1).Delete
Worksheets(1).Name = fn
.SaveAs Filename:=fp & Chr(92) & fn, FileFormat:=51
.Close savechanges:=False '<~~ already saved in line above
End With
End With
Next w
End With
bm_Safe_Exit:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub ```
The code below worked for me: not sure exactly where the problem might vbe with your posted code, but within your With blocks not everything is scope to the block using a leading .
Sub Test()
Dim w As Long, wb As Workbook, wbNew As Workbook
Dim fp As String, fn As String
Dim fsoFSO
On Error GoTo bm_Safe_Exit
Set wb = ThisWorkbook
fp = "C:\Users\Username\OneDrive - CompanyName\Documents\Projects\" & _
"ThisProject\csvOutput\" & Format(Date, "ddmmyyyy") & "\"
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
If fsoFSO.FolderExists(fp) Then
MsgBox "FOLDER - " & fp & " ALREADY EXISTS, DELETE CONTENTS TO PROCEED"
Exit Sub
Else
fsoFSO.CreateFolder fp
End If
'cycle through each of the worksheets
For w = 6 To wb.Worksheets.Count
'explicitly create a new single-sheet workbook as the destination
Set wbNew = Workbooks.Add(Template:=xlWBATWorksheet)
wb.Worksheets(w).Copy before:=wbNew.Sheets(1)
DeleteSheet wbNew.Sheets(2)
With wbNew
fn = .Worksheets(1).Name
.Worksheets.Add after:=.Worksheets(.Worksheets.Count)
.Worksheets(1).Cells.SpecialCells(xlCellTypeVisible).Copy _
Destination:=.Worksheets(2).Range("A1")
DeleteSheet .Worksheets(1)
.Worksheets(1).Name = fn
.SaveAs Filename:=fp & fn, FileFormat:=51
.Close savechanges:=False '<~~ already saved in line above
End With
Next w
Exit Sub
bm_Safe_Exit:
MsgBox Err.Description
End Sub
'utility sub
Sub DeleteSheet(ws As Worksheet)
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End Sub

VBA to copy workbook and keep relative cell references between sheets

I have workbook that has multiple sheets and need a macro button to save a copy of it and delete the sheet named "CSG". This was easy to do, but the problem was that all cell references pointed to the original workbook.
With help, the problem has been tried to solve through name manager and break all links-code. Now the problem is that it break all references within the new workbook and copies only the values from the original workbook.
For example, in the original workbook sheet1 cell A1 has value 10, sheet2 cell A1 has cell reference "='sheet1'!A1". When I make the new copy, both cells do have the value 10, but the reference is no longer there.
Is there a way to keep these references within the workbook without them referencing the original workbook? Below is the code currently being used.
Sub SaveTest()
Dim x As Integer
Dim FileName As String, FilePath As String
Dim NewWorkBook As Workbook, OldWorkBook As Workbook
Set OldWorkBook = ThisWorkbook
With Application
.ScreenUpdating = False: .DisplayAlerts = False
End With
On Error Resume Next
With OldWorkBook.Sheets("CSG")
FilePath = "C:\Users\Tom\Desktop\" & .Range("B1").Value & " " & .Range("B2").Value
FileName = .Range("B1").Value & " " & .Range("B2").Value & ".xlsx"
End With
MkDir FilePath
On Error GoTo -1
On Error GoTo myerror
FilePath = FilePath & "\"
For x = 2 To OldWorkBook.Worksheets.Count
With OldWorkBook.Worksheets(x)
If Not NewWorkBook Is Nothing Then
.Copy after:=NewWorkBook.Worksheets(NewWorkBook.Worksheets.Count)
Else
.Copy
Set NewWorkBook = ActiveWorkbook
End If
End With
Next x
DeleteBadNames NewWorkBook
BreakAllLinks NewWorkBook
UpdateNameManager NewWorkBook
NewWorkBook.SaveAs FilePath & FileName, 51
myerror:
If Not NewWorkBook Is Nothing Then NewWorkBook.Close False
With Application
.ScreenUpdating = True: .DisplayAlerts = True
End With
If Err <> 0 Then MsgBox (Error(Err)), 48, "Error"
End Sub
Create a Copy of a Workbook
Option Explicit
Sub SaveTest()
Dim OldWorkBook As Workbook: Set OldWorkBook = ThisWorkbook
Dim WorkSheetNames() As String
Dim FilePath As String
Dim FileName As String
With OldWorkBook.Worksheets("CSG")
ReDim WorkSheetNames(1 To .Parent.Worksheets.Count)
FilePath = "C:\Users\Tom\Desktop\" & .Range("B1").Value & " " _
& .Range("B2").Value
FileName = .Range("B1").Value & " " & .Range("B2").Value & ".xlsx"
End With
On Error Resume Next
MkDir FilePath
On Error GoTo 0
FilePath = FilePath & "\"
Dim ws As Worksheet
Dim n As Long
For Each ws In OldWorkBook.Worksheets
n = n + 1
WorkSheetNames(n) = ws.Name
Next ws
Application.ScreenUpdating = False
OldWorkBook.Worksheets(WorkSheetNames).Copy
With ActiveWorkbook ' new workbook
Application.DisplayAlerts = False
.Worksheets("CSG").Delete
.SaveAs FilePath & FileName, 51 ' xlOpenXMLWorkbook
Application.DisplayAlerts = True
'.Close SaveChanges:=False
End With
Application.ScreenUpdating = True
End Sub

Copying collections of sheets identified by name list to new workbooks

I am trying to copy specific collections sheets within an excel workbook in separate workbooks. Not being a vba coder I have used and adapted code found here and other resource sites. I believe I am now very close having grasped the basic concepts but cannot figure out what i am doing wrong, triggering the below code causes the first new workbook to be created and the first sheet inserted but breaks at that point.
My code is below, additional relevant info - there is a sheet called 'List' which has a column of names. Each name on the list has 2 sheets which I am trying to copy 2 by 2 into new sheet of the same name. the sheets are labelled as the name and the name + H (e.g Bobdata & BobdataH)
Sub SheetCreate()
'
'Creates an individual workbook for each worksname in the list of names.
'
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sht As Object
Dim strSavePath As String
Dim sname As String
Dim relativePath As String
Dim ListOfNames As Range, LRow As Long, Cell As Range
With ThisWorkbook
Set ListSh = .Sheets("List")
End With
LRow = ListSh.Cells(Rows.Count, "A").End(xlUp).Row '--Get last row of list.
Set ListOfNames = ListSh.Range("A1:A" & LRow) '--Qualify list.
With Application
.ScreenUpdating = False '--Turn off flicker.
.Calculation = xlCalculationManual '--Turn off calculations.
End With
Set wbSource = ActiveWorkbook
For Each Cell In ListOfNames
sname = Cell.Value & ".xls"
relativePath = wbSource.Path & "\" & sname
Sheets(Cell.Value).Copy
Set wbDest = ActiveWorkbook
Application.DisplayAlerts = False
ActiveWorkbook.CheckCompatibility = False
ActiveWorkbook.SaveAs Filename:=relativePath, FileFormat:=xlExcel8
Application.DisplayAlerts = True
wbSource.Activate
Sheets(Cell.Value & "H").Copy after:=Workbooks(relativePath).Sheets(Cell.Value)
wbDest.Save
wbDest.Close False
Next Cell
MsgBox "Done!"
End Sub
You can try to change
Sheets(Cell.Value & "H").Copy after:=Workbooks(relativePath).Sheets(Cell.Value)
to
Sheets(Cell.Value & "H").Copy after:=wbDest.Sheets(Cell.Value)
Also it would be good idea to check if file already exists in selected location. For this you can use function:
Private Function findFile(ByVal sFindPath As String, Optional sFileType = ".xlsx") As Boolean
Dim obj_fso As Object: Set obj_fso = CreateObject("Scripting.FileSystemObject")
findFile = False
findFile = obj_fso.FileExists(sFindPath & "/" & sFileType)
Set obj_fso = Nothing
End Function
and change sFileType = ".xlsx" to "*" or other excet file type.
This was the code i created to create a new workbook and then copy sheet contents from existing one to the new one. Hope it helps.
Private Sub CommandButton3_Click()
On Error Resume Next
Application.ScreenUpdating = False
Application.DisplayAlerts = False
TryAgain:
Flname = InputBox("Enter File Name :", "Creating New File...")
MsgBox Len(Flname)
If Flname <> "" Then
Set NewWkbk = Workbooks.Add
ThisWorkbook.Sheets(1).Range("A1:J100").Copy
NewWkbk.Sheets(1).Range("A1:J100").PasteSpecial
Range("A1:J100").Select
Selection.Columns.AutoFit
AddData
Dim FirstRow As Long
Sheets("Sheet1").Range("A1").Value = "Data Recorded At-" & Format(Now(), "dd-mmmm-yy-h:mm:ss")
NewWkbk.SaveAs ThisWorkbook.Path & "\" & Flname
If Err.Number = 1004 Then
NewWkbk.Close
MsgBox "File Name Not Valid" & vbCrLf & vbCrLf & "Try Again."
GoTo TryAgain
End If
MsgBox "Export Complete Close the Application."
NewWkbk.Close
End If
End Sub

Export only sheets in listbox

I have a Userform with a Listbox and a Export button. The Listbox will list all the Sheet names in the workbook. I want to be able to select the sheet names in the list box and click on export to make a copy in the desktop that creates a paste only value & formatting (without the formula and form buttons on the original sheet).
So for I was successful in listing the sheet name in the listbox, but I am having some trouble with the export button code, I get out of range error.
Private Sub CommandButton1_Click()
Dim lSht As Long
Dim wb As Workbook
Dim sPath As String
Dim sSheet As String
Dim NewWbName As String
Dim i As Long
'Set variables
Set wb = Workbooks.Add
'Add a filepath to your computer below
sPath = "C:\Users\" & Environ("USERNAME") & "\Desktop\"
NewWbName = "Reports " & Format(Now, "yyyy_mm_dd _hh_mm")
i = 1
'Loop through listbox
For lSht = 0 To Me.sheetlist.ListCount - 1
'check if items selected
If Me.sheetlist.Selected(lSht) = True Then
'copy out the sheet and saveas
sSheet = Me.sheetlist.List(lSht)
With wb.Worksheets(sSheet).Copy
.PasteSpecial (xlPasteValues)
.PasteSpecial (xlPasteFormats)
End With
Application.DisplayAlerts = False
wb.SaveAs Filename:=DesktopPath & NewWbName, FileFormat:=xlNormal
wb.Close
MsgBox "You can find the export file in your desktop.", vbOKOnly + vbInformation, "Back Up Sucessful!"
Application.DisplayAlerts = True
End If
Next lSht
End Sub
Following or comments above, try the code below:
Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim newWb As Workbook
Dim sPath As String
Dim sSheet As String
Dim NewWbName As String
Dim lSht As Long
Dim NewSht As Worksheet
Dim i As Long
Dim firstExport As Boolean
'Set variables
Set wb = ThisWorkbook
Set newWb = Workbooks.Add
Application.DisplayAlerts = False
firstExport = True
'Add a filepath to your computer below
sPath = "C:\Users\" & Environ("USERNAME") & "\Desktop\"
NewWbName = "Reports " & Format(Now, "yyyy_mm_dd _hh_mm")
'Loop through listbox
For lSht = 0 To Me.sheetlist.ListCount - 1
'check if items selected
If Me.sheetlist.Selected(lSht) = True Then
'copy out the sheet and saveas
sSheet = Me.sheetlist.List(lSht)
If firstExport Then
firstExport = False
' remove all sheets (exceot 1) in first Copy>Paste
For i = newWb.Sheets.Count - 1 To 1 Step -1
newWb.Sheets(i).Delete
Next i
' add new sheet to new workbook and put it at theend
Set NewSht = newWb.Sheets(newWb.Sheets.Count)
Else
' add new sheet to new workbook and put it at the end
Set NewSht = newWb.Sheets.Add(After:=newWb.Sheets(newWb.Sheets.Count))
End If
NewSht.Name = sSheet
With wb.Sheets(sSheet)
.Cells.Copy
NewSht.Cells.PasteSpecial (xlPasteValues)
NewSht.Cells.PasteSpecial (xlPasteFormats)
End With
End If
Next lSht
' need to move the save workbook outside the Copy all selected sheets "loop"
newWb.SaveAs Filename:=sPath & NewWbName, FileFormat:=xlNormal
newWb.Close True
MsgBox "You can find the export file in your desktop.", vbOKOnly + vbInformation, "Back Up Sucessful!"
Application.DisplayAlerts = True
End Sub

Resources