Export only sheets in listbox - excel

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

Related

Excel Checkbox Selected sheets to Another Worksheet

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

Splitting Sheets with Same Name Range in One Excel Workbook - Excel VBA

I have some Excel workbooks which contains more than 100 sheets. The sheet names like below;
TTBMA2453_Speclist, TTBMA2454_Speclist, TTBMA2455_Speclist and goes on..
WBXXTTBMA2453_Featurelist, WBXXTTBMA2454_Featurelist, WBXXTTBMA2455_Featurelist and goes on..
WBXXTTBMA2453_Corelist, WBXXTTBMA2454_Corelist, WBXXTTBMA2455_Corelist and goes on..
I want to split all spec, feature and corelist sheets which are starting with same speclist name in the same workbook and merge/save to another Excel workbook in a specific file using Excel VBA.
(e.g combining TTBMA2453_Speclist, WBXXTTBMA2453_Featurelist WBXXTTBMA2453_Corelist and copy them as new workbook with original sheets)
Please find the code sample I have. This code splits sheets of the same name (which I added manually) into workbooks. However, this code does not re-merge the sheets in a different workbook and sheet names are entered manually. So, that's not what I want.
Sub SplitEachWorksheet()
Dim FPath As String
FPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim ws As Worksheet
Dim fnameList, fnameCurFile As Variant
Dim countFiles, countSheets As Integer
Dim wksCurSheet As Worksheet
Dim wbkCurBook, wbkSrcBook As Workbook
For Each ws In ThisWorkbook.Worksheets
If Left$(ws.Name, 9) = "TTBMA2453" Then ' <--- added an IF statement
ws.Copy
Application.ActiveWorkbook.SaveAs Filename:=FPath & "\" & ws.Name & ".xlsx"
Application.ActiveWorkbook.Close False
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Option Explicit
Sub SplitEachWorksheet()
Dim wb As Workbook, wbNew As Workbook, ws As Worksheet
Dim num As Collection, n, dict As Object
Dim FPath As String
FPath = Application.ActiveWorkbook.Path
Set num = new Collection
Set dict = CreateObject("Scripting.Dictionary")
Set wb = ThisWorkbook
For Each ws In wb.Worksheets
If ws.Name Like "*_Speclist" Then
num.Add Left(ws.Name, Len(ws.Name) - 9)
End If
dict.Add ws.Name, ws.Index
Next
' check sheets
Dim msg As String, s As String
For Each n In num
s = "WBXX" & n & "_Corelist"
If Not dict.exists(s) Then
msg = msg & vbLf & s & " missing"
End If
s = "WBXX" & n & "_Featurelist"
If Not dict.exists(s) Then
msg = msg & vbLf & s & " missing"
End If
Next
If Len(msg) > 0 Then
MsgBox msg, vbCritical
Exit Sub
End If
' check workbooks
Application.ScreenUpdating = False
For Each n In num
wb.Sheets(n & "_Speclist").Copy
Set wbNew = ActiveWorkbook
wb.Sheets("WBXX" & n & "_Featurelist").Copy after:=wbNew.Sheets(1)
wb.Sheets("WBXX" & n & "_Corelist").Copy after:=wbNew.Sheets(2)
wbNew.SaveAs Filename:=FPath & "\" & n
wbNew.Close False
Next
Application.ScreenUpdating = True
' result
MsgBox num.Count & " worksbooks created in " & FPath, vbInformation
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

Copy rows of multiple workbooks into one main workbook

I want to open a workbook that contains only one sheet,
copy data up to column AC until last available row in column A,
paste the data into first empty row in column A in workbook "Mergedsheet.xlsx".
I want to loop over all workbooks present in a specific folder, but get lots of errors.
Sub MergeNew()
Dim WorkBk As Workbook
Dim MergedSheet As Worksheet
Dim SourceData As Range
Dim DestinationData As Range
Dim lastRow As Long
Dim NextRow As Range
Dim FolderPath As String
Dim FileNames As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FolderPath = "E:\Jan to March 2019\Bharuch 31\"
FileNames = Dir(FolderPath & "*.xls*")
Do While FileNames <> ""
Set WorkBk = Workbooks.Open(FolderPath & FileNames)
Range("A1:AC1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Workbooks.Open Filename:="E:\Jan to March 2019\Bharuch 31\MergedSheet.xlsx"
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow).Select
ActiveSheet.Paste
'ActiveWindow.Close SaveChanges:=True
'ActiveWindow.Close SaveChanges:=False
Application.CutCopyMode = False
FileNames = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
You are looping through a folder and copy-pasting each workbook's first sheet's data to workbook A. However, workbook A is also in that folder. So you should take care to skip it (when looping).
(Alternatively, you could provide a different argument to the DIR function (e.g. some wildcard criteria that excludes workbook A if possible), so that you don't have to constantly check inside the loop.)
Untested.
Option Explicit
Private Sub MergeNew()
'Application.ScreenUpdating = False 'Uncomment this when you know code is working.
'Application.DisplayAlerts = False 'Uncomment this when you know code is working.
Dim folderPath As String
folderPath = GetFolderPath(titleToShow:="Select the folder containing the files to loop through.")
Dim Filename As String
Filename = Dir$(folderPath & "*.xls*")
If Len(Filename) = 0 Then
MsgBox "Could not find a relevant file in '" & folderPath & "'. Code will stop running now."
Exit Sub ' No point in carrying on in such a case.
End If
Dim destinationFolderPath As String
destinationFolderPath = GetFolderPath(titleToShow:="Select the folder to save the 'MergedSheet.xlsx' file to.")
Dim destinationWorkbook As Workbook
Set destinationWorkbook = Application.Workbooks.Add
' This line may throw an error
destinationWorkbook.SaveAs Filename:=destinationFolderPath & "MergedSheet.xlsx", FileFormat:=xlOpenXMLWorkbook
Dim destinationSheet As Worksheet
Set destinationSheet = destinationWorkbook.Worksheets(1) ' I assume there's only 1 sheet in there, but change as necessary.
Do Until Len(Filename) = 0
Dim fullFilePathToOpen As String
fullFilePathToOpen = folderPath & Filename
If fullFilePathToOpen <> destinationWorkbook.FullName Then ' Probably could have just compared filename since directory is the same, but this is more explicit
Dim sourceWorkbook As Workbook
Set sourceWorkbook = Application.Workbooks.Open(Filename:=fullFilePathToOpen, ReadOnly:=True) ' If you don't make changes to the workbook you open, better to open as read-only
Dim sourceSheet As Worksheet
Set sourceSheet = sourceWorkbook.Worksheets(1) ' You say there's only one worksheet in there, so referring by index should be okay (for now)
Dim lastSourceRow As Long
lastSourceRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row ' Assume last row can be determined from column A alone
Dim lastDestinationRow As Long
lastDestinationRow = destinationSheet.Cells(destinationSheet.Rows.Count, "A").End(xlUp).Row + 1
If destinationSheet.Rows.Count < (lastDestinationRow + lastSourceRow) Then
MsgBox "Ran out of rows (in sheet '" & sourceSheet.Name & "' of workbook '" & destinationWorkbook.Name & "')"
Exit Sub
End If
sourceSheet.Range("A1", sourceSheet.Cells(lastSourceRow, "AC")).Copy Destination:=destinationSheet.Cells(lastDestinationRow, "A")
sourceWorkbook.Close False
End If
Filename = Dir$()
Loop
'Application.ScreenUpdating = True 'Uncomment this when you know code is working.
'Application.DisplayAlerts = True 'Uncomment this when you know code is working.
End Sub
Private Function GetFolderPath(Optional ByVal titleToShow As String = vbNullString) As String
With Application.FileDialog(msoFileDialogFolderPicker)
If Len(titleToShow) > 0 Then .Title = titleToShow
.AllowMultiSelect = False ' Only one is allowed.
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Folder selection appears to have cancelled. Code will stop running now"
End
End If
GetFolderPath = .SelectedItems(1) & "\"
End With
End Function

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

Resources