Excel VBA open & save as - vba

I have managed to open a series of excel workbooks based on values in cells, but am struggling to programme the save as. Can you help me to enable save as after opening each workbook?
I want the file name linked to two cells and the file path derived from a cell using =LEFT(CELL("filename"),SEARCH("[",CELL("filename"))-1)
Sub Open_Workbooks()
Dim SourcePath As String
Dim SourceFile1 As String
Dim SourceFile2 As String
Dim bIsEmpty As Boolean
Dim relativePath As String
Dim sname1 As String
Dim sname2 As String
Dim Ret1
Dim Ret2
Dim PathName1 As String
Dim PathName2 As String
SourcePath = "G:\x\y\"
SourceFile1 = Workbooks("r.xlsm").Sheets("Front sheet").Range("Z1").Text
SourceFile2 = Workbooks("r.xlsm").Sheets("Front sheet").Range("Z2").Text
sname1 = Workbooks("r.xlsm").Sheets("Front sheet").Range("AA1").Text
sname2 = Workbooks("r.xlsm").Sheets("Front sheet").Range("AA2").Text
Ret1 = IsWorkBookOpen("G:\x\y\TEMPLATE.xlsm")
Ret2 = IsWorkBookOpen("G:\x\y\TEMPLATE2.xlsm")
relativePath = Workbooks("r.xlsm").Sheets("Front sheet").Range("H13").Text
PathName1 = Workbooks("r.xlsm").Sheets("Front sheet").Range("H13").Text & Workbooks("r.xlsm").Sheets("Front sheet").Range("AA1").Text & "xlsm"
PathName2 = relativePath & sname2 & "xlsm"
bIsEmpty = False
If IsEmpty(Workbooks("r.xlsm").Sheets("Front sheet").Range("Z1")) = False Then
'Workboks.Open "G:\x\y\" & Range("[wardchart]").Text & Range("[code]").Text & ".xlsm", ReadOnly:=True
Workbooks.Open SourcePath & SourceFile1 & ".xlsm", ReadOnly:=False
ElseIf IsEmpty(Workbooks("Rates, percentages calculator.xlsm").Sheets("Front sheet").Range("Z1")) = True Then
bIsEmpty = True
End If
On Error Resume Next
If Ret1 = True Then
'ThisWorkbook.SaveAs PathName1, xlOpenXMLMacroEnabled, CreateBackup:=False
ThisWorkbook.SaveCopyAs PathName1
ElseIf Ret1 = False Then
bIsEmpty = True
End If
On Error Resume Next
End Sub

I resolved this with a file copy to path and then a subsequent open:
Sub CopyRenameFile()
Dim src As String, dst As String, f1 As String, f2 As String
Dim rf1 As String, rf2 As String
'source directory
src = Workbooks("r.xlsm").Sheets("Front sheet").Range("AC1").Text
'destination directory
dst = Workbooks("r.xlsm").Sheets("Front sheet").Range("AB1").Text
'file name
f1 = Workbooks("r.xlsm").Sheets("Front sheet").Range("Z1").Text
'file name
f2 = Workbooks("r.xlsm").Sheets("Front sheet").Range("Z2").Text
'rename file
rf1 = Workbooks("r.xlsm").Sheets("Front sheet").Range("AA1").Text
'rename file
rf2 = Workbooks("r.xlsm").Sheets("Front sheet").Range("AA2").Text
On Error Resume Next
If IsEmpty(Workbooks("r.xlsm").Sheets("Front sheet").Range("Z1")) = False Then
FileCopy src & f1 & ".xlsm", dst & rf1 & ".xlsm"
End If
On Error GoTo 0
On Error Resume Next
If IsEmpty(Workbooks("r.xlsm").Sheets("Front sheet").Range("Z2")) = False Then
FileCopy src & f2 & ".xlsm", dst & rf2 & ".xlsm"
End If
On Error GoTo 0
End Sub

I'm not completely sure whether I could help you with this issue but perhaps this might help getting you in the right direction:
Sub Copy_ActiveSheet_1()
'Working in Excel 97-2017
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set Sourcewb = ActiveWorkbook
'Copy the sheet to a new workbook
ActiveSheet.Copy
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
Select Case Sourcewb.FileFormat
Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
Case 52:
If .HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 52
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
Case 56: FileExtStr = ".xls": FileFormatNum = 56
Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
End With
' 'Change all cells in the worksheet to values if you want
' With Destwb.Sheets(1).UsedRange
' .Cells.Copy
' .Cells.PasteSpecial xlPasteValues
' .Cells(1).Select
' End With
' Application.CutCopyMode = False
'Save the new workbook and close it
TempFilePath = Application.DefaultFilePath & "\"
TempFileName = "Part of " & Sourcewb.Name & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")
With Destwb
.SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
.Close SaveChanges:=False
End With
MsgBox "You can find the new file in " & TempFilePath
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Sub Copy_ActiveSheet_2()
'Working in Excel 2000-2016
Dim fname As Variant
Dim NewWb As Workbook
Dim FileFormatValue As Long
'Check the Excel version
If Val(Application.Version) < 9 Then Exit Sub
If Val(Application.Version) < 12 Then
'Only choice in the "Save as type" dropdown is Excel files(xls)
'because the Excel version is 2000-2003
fname = Application.GetSaveAsFilename(InitialFileName:="", _
filefilter:="Excel Files (*.xls), *.xls", _
Title:="This example copies the ActiveSheet to a new workbook")
If fname <> False Then
'Copy the ActiveSheet to new workbook
ActiveSheet.Copy
Set NewWb = ActiveWorkbook
'We use the 2000-2003 format xlWorkbookNormal here to save as xls
NewWb.SaveAs fname, FileFormat:=-4143, CreateBackup:=False
NewWb.Close False
Set NewWb = Nothing
End If
Else
'Give the user the choice to save in 2000-2003 format or in one of the
'new formats. Use the "Save as type" dropdown to make a choice,Default =
'Excel Macro Enabled Workbook. You can add or remove formats to/from the list
fname = Application.GetSaveAsFilename(InitialFileName:="", filefilter:= _
" Excel Macro Free Workbook (*.xlsx), *.xlsx," & _
" Excel Macro Enabled Workbook (*.xlsm), *.xlsm," & _
" Excel 2000-2003 Workbook (*.xls), *.xls," & _
" Excel Binary Workbook (*.xlsb), *.xlsb", _
FilterIndex:=2, Title:="This example copies the ActiveSheet to a new workbook")
'Find the correct FileFormat that match the choice in the "Save as type" list
If fname <> False Then
Select Case LCase(Right(fname, Len(fname) - InStrRev(fname, ".", , 1)))
Case "xls": FileFormatValue = 56
Case "xlsx": FileFormatValue = 51
Case "xlsm": FileFormatValue = 52
Case "xlsb": FileFormatValue = 50
Case Else: FileFormatValue = 0
End Select
'Now we can create/Save the file with the xlFileFormat parameter
'value that match the file extension
If FileFormatValue = 0 Then
MsgBox "Sorry, unknown file extension"
Else
'Copies the ActiveSheet to new workbook
ActiveSheet.Copy
Set NewWb = ActiveWorkbook
'Save the file in the format you choose in the "Save as type" dropdown
NewWb.SaveAs fname, FileFormat:= _
FileFormatValue, CreateBackup:=False
NewWb.Close False
Set NewWb = Nothing
End If
End If
End If
End Sub

Related

Saving as plain text

I have a code which guys on here helped me with.
This issue is it saves to a shared drive and the info in the cells is still linked to the master copy of the workbook. Is there way to save it as text and not a link?
Sub Sample()
Dim i As Long
Dim DateString As String
Dim wbName As String
If Val(Application.Version) < 12 Then
FileExtStr = ".xls": FileFormatNum = -4143
Else
Select Case ThisWorkbook.FileFormat
Case 51:
FileExtStr = ".xlsx": FileFormatNum = 51
Case 52:
If Application.ActiveWorkbook.HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 52
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
Case 56:
FileExtStr = ".xls": FileFormatNum = 56
Case Else:
FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
'~~> Get file name without extension
wbName = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
'~~> Final folder path
FolderPath = "F:\Orders" & "\" & wbName
'~~> Check if folder exists. If it doesn't then create it
If Not FolderExists(FolderPath) Then MkDir FolderPath
'~~> Loop through the worksheets and save them
For i = 3 To 18
If ThisWorkbook.Sheets(i).Visible Then
RenameAndSaveSheet ThisWorkbook.Sheets(i)
End If
Next i
End Sub
Here is the renameandsave
Private Sub RenameAndSaveSheet(ws As Worksheet)
Dim FlName As String
Dim wbNew As Workbook
With ws
.Copy
.Name = .Range("B1").Value2
FlName = FolderPath & "\" & ws.Name & FileExtStr
Set wbNew = Application.Workbooks.Item(Application.Workbooks.Count)
wbNew.SaveAs FlName, FileFormat:=FileFormatNum
wbNew.Close False
End With
End Sub
Thanks for any help.
If you just want to break all the links make a Function that does that:
' Break all Excel Links found in given worksheet
Public Sub BreakAllLinks(ByVal thisWorkbook As Workbook)
Dim theseLinks As Variant
theseLinks = thisWorkbook.LinkSources(Type:=xlLinkTypeExcelLinks)
If Not IsEmpty(theseLinks) Then
Dim i As Long
For i = 1 To UBound(theseLinks)
thisWorkbook.BreakLink Name:=theseLinks(i), Type:=xlLinkTypeExcelLinks
Next i
End If
End Sub
Then you call that before you save it:
Public Sub RenameAndSaveSheet(ws As Worksheet)
Dim FlName As String
Dim wbNew As Workbook
With ws
.Copy
.Name = .Range("B1").Value2
FlName = FolderPath & "\" & .Name & FileExtStr
End With
Set wbNew = ActiveWorkbook
BreakAllLinks wbNew
wbNew.SaveAs FlName, FileFormat:=FileFormatNum
wbNew.Close False
End Sub

Mailing Multiple Sheets and a Specific Range Within One Sheet

I am trying to write a macro that will email all of Sheet 1 and Range("A7:P20") from Sheet 3. I copied the following code below, which works for sending entire sheets, but I am unsure how to adjust it so I only send the aforementioned range from Sheet 3 on a distinct sheet in addition to all of Sheet 1.
Sub Mail_Sheets_Array()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim TheActiveWindow As Window
Dim TempWindow As Window
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set Sourcewb = ActiveWorkbook
'Copy the sheets to a new workbook
'We add a temporary Window to avoid the Copy problem
'if there is a List or Table in one of the sheets and
'if the sheets are grouped
With Sourcewb
Set TheActiveWindow = ActiveWindow
Set TempWindow = .NewWindow
.Sheets(Array("Sheet1", "Sheet3")).Copy
End With
'Close temporary Window
TempWindow.Close
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
Select Case Sourcewb.FileFormat
Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
Case 52:
If .HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 52
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
Case 56: FileExtStr = ".xls": FileFormatNum = 56
Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
End With
' 'Change all cells in the worksheets to values if you want
' For Each sh In Destwb.Worksheets
' sh.Select
' With sh.UsedRange
' .Cells.Copy
' .Cells.PasteSpecial xlPasteValues
' .Cells(1).Select
' End With
' Application.CutCopyMode = False
' Destwb.Worksheets(1).Select
' Next sh
'Save the new workbook/Mail it/Delete it
TempFilePath = Environ$("temp") & "\"
TempFileName = "Part of " & Sourcewb.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With Destwb
.SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
On Error Resume Next
With OutMail
.to = "ron#debruin.nl"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.Body = "Hi there"
.Attachments.Add Destwb.FullName
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
On Error GoTo 0
.Close savechanges:=False
End With
'Delete the file you have send
Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
You can add this code after Set Destwb = ActiveWorkbook.
Dim LastRowDest as Long
Dim LastColDest as Long
Destwb.sheets("sheet3").Select
LastRowDest = Destwb.sheets("sheet3").cells(rows.count,1).end(xlup).row
LastColDest = Destwb.sheets("sheet3").cells(1,columns.count).end(xltoleft).column
sheets("sheet3").Rows("21:" & LastRowDest + 1).Delete
sheets("sheet3").Rows("1:6").Delete
sheets("sheet3").columns("17:& LastColDest + 1).Delete
Hope this help.

How to save/overwrite the newly created copy of excel workbook with an appended name to a new partition

I have been working on a small automation project where I can send my workbook to a friend by saving it on a server and also by sending emails(now the server part is not important and I will work on it later).
Now I have been able to create a new file and copy all the contents. What I have done is copy all the sheets and save it in a new folder in the same directory. What I really want to do is create a new directory in a different partition say D:\Excel and save it in there with each of my friends having their own file names. And I also want to append the current date to the filename of the new workbook that is created and if a filename with date already exists for the particular friend, I want the new file to overwrite the existing file.
I have for this project already automated the sending of emails and the only problem there has been that I have not been able to send the email at a preset time.Whenever I click on send email,it goes automatically rather than the set time. Can anyone show me the right way to automate these things?
Private Sub Create_Click()
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim dUMMY1 As Workbook
Dim Destwb As Workbook
Dim sh As Worksheet
Dim DateString As String
Dim FolderName As String
Dim dt As String, wbNam As String
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
'Copy every sheet from the workbook with this macro
Set dUMMY1 = ThisWorkbook
'Create new folder to save the new files in
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = dUMMY1.Path & "\" & dUMMY1.Name & " " & DateString
MkDir FolderName
'Copy every visible sheet to a new workbook
For Each sh In dUMMY1.Worksheets
'If the sheet is visible then copy it to a new workbook
If sh.Visible = -1 Then
sh.Copy
'Set Destwb to the new workbook
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2013
If dUMMY1.Name = .Name Then
MsgBox "Your answer is NO in the security dialog"
GoTo GoToNextSheet
Else
Select Case dUMMY1.FileFormat
Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
Case 52:
If .HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 52
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
Case 56: FileExtStr = ".xls": FileFormatNum = 56
Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
End If
End With
'Change all cells in the worksheet to values if you want
If Destwb.Sheets(1).ProtectContents = False Then
With Destwb.Sheets(1).UsedRange
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells(1).Select
End With
Application.CutCopyMode = False
End If
'Save the new workbook and close it
With Destwb
.SaveAs FolderName _
& "\" & Destwb.Sheets(1).Name & FileExtStr, _
FileFormat:=FileFormatNum
.Close False
End With
End If
GoToNextSheet:
Next sh
MsgBox "You can find the files in " & FolderName
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
End With
End Sub
Private Sub Send_Click()
Dim OutApp As Object
Dim OutMail As Object
Application.OnTime TimeValue("15:45:00"), "Auto_Update"
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "abc#def.com"
.CC = ""
.BCC = ""
.Subject = "Testing "
.Body = ""
.Attachments.Add ActiveWorkbook.FullName
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Here is the file that I have been working on:
https://drive.google.com/open?id=0B7uN4B3mxUlZUjV6VnpLdUpQeEU

Creating new workbook from the template that exist in the current workbook

Here is what I have, need to be able to save any template called in ComboBox as separate workbook without any macro in the new one, but with preserving formulas with internal references, rest should be converted to values.
Hear is my attempt to do so, which clearly did not work, since it is saving an active sheet, instead of the template Which is selected. also because of validation, that is necessary, I am forced to use part of the code twice, is there any way of doing it in any different way.
I think I also need to mention that ComboBox is on UserForm.
Please help me
'Continue to create your invoice and check for the archive folder existance
Private Sub ContinueButton_Click()
If cmbSheet.Value = "" Then
MsgBox "Please select the Invoice Template from the list to continue."
ElseIf cmbSheet.Value <> 0 Then
Dim response
Application.ScreenUpdating = 0
Sheets(cmbSheet.Value).Visible = True
'Creating the directory only if it doesn't exist
directoryPath = getDirectoryPath
If Dir(directoryPath, vbDirectory) = "" Then
response = MsgBox("The directory " & Settings.Range("_archiveDir").Value & " does not exist. Would you like to create it?", vbYesNo)
If response = vbYes Then
createDirectory directoryPath
MsgBox "The folder has been created. " & directoryPath
'Application.Goto Sheets(cmbSheet.Value).[a22], True
Application.ScreenUpdating = False
Else
MsgBox "You need to create new folder " & Settings.Range("_archiveDir").Value & " to archive your invoices prior to creating them."
Unload Me
End If
Unload Me
ElseIf Dir(directoryPath, vbDirectory) <> directoryPath Then
'Working in Excel 97-2007
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim newFile As String, fName As String
Dim sep As String
sep = Application.PathSeparator
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set Sourcewb = ActiveWorkbook
'Copy the sheet to a new workbook
ActiveSheet.Copy
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007
'We exit the sub when your answer is NO in the security dialog that you
'only see when you copy a sheet from a xlsm file with macro's disabled.
If Sourcewb.Name = .Name Then
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox "Your answer is NO in the security dialog"
Exit Sub
Else
Select Case Sourcewb.FileFormat
Case 51: FileExtStr = ".xlsx": FileFormatNum = 56
Case 52:
If .HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 56
Else
FileExtStr = ".xlsx": FileFormatNum = 56
End If
Case 56: FileExtStr = ".xls": FileFormatNum = 56
Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
End If
End With
' 'If you want to change all cells in the worksheet to values, uncomment these lines.
' With Destwb.Sheets(1).UsedRange
' .Cells.Copy
' .Cells.PasteSpecial xlPasteValues
' .Cells(1).Select
' End With
' Application.CutCopyMode = False
'Save the new workbook and close it
fName = Range("I11").Value
'Change the date format to whatever you'd like, but make sure it's in quotes
newFile = fName & " " & Format$(Date, "mm-dd-yyyy") & Columns("M:N").Select
Selection.Delete Shift:=xlToLeft
TempFilePath = directoryPath & sep
TempFileName = "New File"
With Destwb
.SaveAs TempFilePath & TempFileName, FileFormat:=FileFormatNum
.Close SaveChanges:=False
End With
MsgBox "You can find the new file in " & TempFilePath
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
'Application.Goto Sheets(cmbSheet.Value).[a22], True
Application.ScreenUpdating = False
Unload Me
End If
End If
End Sub
As it is the template sheet that you want to copy, you probably want to do Sourcewb.Sheets(cmbSheet.Value).Copy instead of ActiveSheet.Copy.
To avoid running the code twice, change this code:
Else
MsgBox "You need to create new folder " & Settings.Range("_archiveDir").Value & " to archive your invoices prior to creating them."
Unload Me
End If
Unload Me
ElseIf Dir(directoryPath, vbDirectory) <> directoryPath Then
to this instead:
Else
MsgBox "You need to create new folder " & Settings.Range("_archiveDir").Value & " to archive your invoices prior to creating them."
Unload Me
End If
End If
If Dir(directoryPath, vbDirectory) <> directoryPath Then
Here is the whole code after my changes
Option Explicit
'Continue to create your invoice and check for the archive folder existance
Private Sub ContinueButton_Click()
If cmbsheet.Value = "" Then
MsgBox "Please select the Invoice Template from the list to continue."
ElseIf cmbsheet.Value <> 0 Then
Dim response
Application.ScreenUpdating = 0
'Creating the directory only if it doesn't exist
directoryPath = getDirectoryPath
If Dir(directoryPath, vbDirectory) = "" Then
response = MsgBox("The directory " & Settings.Range("_archiveDir").Value & " does not exist. Would you like to create it?", vbYesNo)
If response = vbYes Then
createDirectory directoryPath
MsgBox "The folder has been created. " & directoryPath
'Application.Goto Sheets(cmbSheet.Value).[a22], True
Application.ScreenUpdating = False
Else
MsgBox "You need to create new folder " & Settings.Range("_archiveDir").Value & " to archive your invoices prior to creating them."
'Unload Me
GoTo THE_END
End If
End If
If Dir(directoryPath, vbDirectory) <> directoryPath Then
Sheets(cmbsheet.Value).Visible = True
'Working in Excel 97-2007
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim newFile As String, fName As String
Dim sep As String
sep = Application.PathSeparator
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set Sourcewb = ActiveWorkbook
'Copy the sheet to a new workbook
Sourcewb.Sheets(cmbsheet.Value).Copy
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007
'We exit the sub when your answer is NO in the security dialog that you
'only see when you copy a sheet from a xlsm file with macro's disabled.
If Sourcewb.Name = .Name Then
'With Application
' .ScreenUpdating = True
' .EnableEvents = True
'End With
MsgBox "Your answer is NO in the security dialog"
'Exit Sub
GoTo THE_END
Else
Select Case Sourcewb.FileFormat
Case 51: FileExtStr = ".xlsx": FileFormatNum = 56
Case 52:
If .HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 56
Else
FileExtStr = ".xlsx": FileFormatNum = 56
End If
Case 56: FileExtStr = ".xls": FileFormatNum = 56
Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
End If
End With
'If you want to change all cells in the worksheet to values, uncomment these lines.
'With Destwb.Sheets(1).UsedRange
With Sourcewb.Sheets(cmbsheet.Value).UsedRange
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells(1).Select
End With
Application.CutCopyMode = False
'Save the new workbook and close it
fName = Range("I11").Value
'Change the date format to whatever you'd like, but make sure it's in quotes
newFile = fName & " " & Format$(Date, "mm-dd-yyyy") & Columns("M:N").Select
Selection.Delete Shift:=xlToLeft
TempFilePath = directoryPath & sep
TempFileName = "New File"
With Destwb
.SaveAs TempFilePath & TempFileName, FileFormat:=FileFormatNum
.Close SaveChanges:=False
End With
MsgBox "You can find the new file in " & TempFilePath
'With Application
' .ScreenUpdating = True
' .EnableEvents = True
'End With
'Application.Goto Sheets(cmbSheet.Value).[a22], True
'Application.ScreenUpdating = False
'Unload Me
End If
End If
THE_END:
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Unload Me
End Sub

Copy another worksheet along if formulas on the main worksheet refert to it Excel VBA

Problem I have is, when I am saving my my worksheet as another workbook using code below I also need to copy additional worksheet only on one occasion when formulas on the worksheet I intend to save refer to the "Price List" worksheet, which I would need to also save along with the first worksheet. I hope it make sense. Also another small problem, when I save worksheet as a new workbook, I need that workbook to open imedietly, so that I can then continue to work with that workbook.
Here is my code
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In Worksheets
If InStr(LCase(ws.Name), "template") <> 0 Then
cmbSheet.AddItem ws.Name
End If
Next ws
End Sub
'Continue to create your invoice and check for the archive folder existance
Private Sub ContinueButton_Click()
If cmbSheet.Value = "" Then
MsgBox "Please select the Invoice Template from the list to continue."
ElseIf cmbSheet.Value <> 0 Then
Dim response
Application.ScreenUpdating = 0
'Creating the directory only if it doesn't exist
directoryPath = getDirectoryPath
If Dir(directoryPath, vbDirectory) = "" Then
response = MsgBox("The directory " & Settings.Range("_archiveDir").Value & " does not exist. Would you like to create it?", vbYesNo)
If response = vbYes Then
createDirectory directoryPath
MsgBox "The folder has been created. " & directoryPath
Application.ScreenUpdating = False
Else
MsgBox "You need to create new folder " & Settings.Range("_archiveDir").Value & " to archive your invoices prior to creating them."
GoTo THE_END
End If
End If
If Dir(directoryPath, vbDirectory) <> directoryPath Then
Sheets(cmbSheet.Value).Visible = True
'Working in Excel 97-2007
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Set Sourcewb = ActiveWorkbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim fName As String
Dim sep As String
sep = Application.PathSeparator
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Copy the sheet to a new workbook
Sourcewb.Sheets(cmbSheet.Value).Copy
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
If Sourcewb.Name = .Name Then
GoTo THE_END
Else
Select Case Sourcewb.FileFormat
Case 51: FileExtStr = ".xlsx": FileFormatNum = 56
End Select
End If
End If
End With
'Copy current colorscheme to the new Workbook
For i = 1 To 56
Destwb.Colors(i) = Sourcewb.Colors(i)
Next i
'If you want to change all cells in the worksheet to values, uncomment these lines.
'With Destwb.Sheets(1).UsedRange
'With Sourcewb.Sheets(cmbSheet.Value).UsedRange
' .Cells.Copy
' .Cells.PasteSpecial xlPasteValues
' .Cells(1).Select
'End With
Application.CutCopyMode = False
'Save the new workbook and close it
Destwb.Sheets(1).Name = "Invoice"
fName = Home.Range("_newInvoice").Value
TempFilePath = directoryPath & sep
TempFileName = fName
With Destwb
.SaveAs TempFilePath & TempFileName, FileFormat:=FileFormatNum
.Close SaveChanges:=False
End With
MsgBox "You can find the new file in " & TempFilePath & TempFileName
End If
End If
THE_END:
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Unload Me
End Sub
If I'm understanding you correctly, based on what you said you need to do two things:
Copy a worksheet when formulas contain references to the "Price List" worksheet
Save the new worksheet as a new workbook and open immediately
Here is code to paste in a module:
Sub IdentifyFormulaCellsAndCopy()
'******** Find all cells that contain formulas and highlight any that refer to worksheet 'price list' **********
Dim ws As Worksheet
Dim rng As Range
Set ws = ActiveSheet
For Each rng In ws.Cells.SpecialCells(xlCellTypeFormulas)
If InStr(LCase(rng.Formula), "price list") <> 0 Then
'Highlight cell if it contains formula
rng.Interior.ColorIndex = 36
End If
Next rng
'*******************************************************************************************************************
'********* Save worksheet as new workbook, then activate and open immediately to begin work on it *******************
'Hide alerts
Application.DisplayAlerts = False
Dim FName As String
Dim FPath As String
Dim NewBook As Workbook
FPath = "C:\Users\User\Desktop"
FName = "CopiedWorksheet " & Format(Date, "yyyy-mm-dd") & ".xls"
'Create a new workbook
Set NewBook = Workbooks.Add
'Copy the 'template' worksheet into new workbook
ThisWorkbook.Sheets("template").Copy Before:=NewBook.Sheets(1)
'If file doesn't already exist, then save new workbook
If Dir(FPath & "\" & FName) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
NewBook.SaveAs Filename:=FPath & "\" & FName
End If
'Activate workbook that you just saved
NewBook.Activate
'Show Alerts
Application.DisplayAlerts = True
'**********************************************************************************************************************
End Sub
Notes:
Depending on how you implement this code, you can add Application.ScreenUpdating = False to speed things up.
Also, this code assumes that you have worksheets with the names of template and Price List.