Macro to copy data from a different workbook - vba

I have a workbook (in Excel 2003 format) with data flowing continuously in three sheets. I want to create a macro in a new workbook (Excel 2010) in which all those data in all the three sheets in the previous workbook to get pasted in a single sheet of my new workbook, one after another. I would prefer the macro to open a dialog box to browse the file where the data is actually present. Can anyone help me please?
While searching I found something like given below. But that is not the one I want exactly.
Sub Open_Workbook()
Dim myFile As String
myFile = Application.GetOpenFilename _
(Title:="Please choose a file to open", _
FileFilter:="Excel Files .xls (.xls),")
If myFile = False Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Workbooks.Open Filename:=myFile
End If
End Sub

I suppose this code will help you
Sub wb_sheets_combine_into_one()
Dim sFileName$, UserName$, oWbname$, oWbname2$, sDSheet$ 'String type
Dim nCountDestination&, nCount&, nCountCol& 'Long type
Dim oSheet As Excel.Worksheet
Dim oRange As Range
Dim oFldialog As FileDialog
Set oFldialog = Application.FileDialog(msoFileDialogFilePicker)
With oFldialog
If .Show = -1 Then
.Title = "Select File"
.AllowMultiSelect = False
sFileName = .SelectedItems(1)
Else
Exit Sub
End If
End With
'open source workbook
Workbooks.Open sFileName: oWbname = ActiveWorkbook.Name
UserName = Environ("username")
Workbooks.Add: ActiveWorkbook.SaveAs Filename:= _
"C:\Users\" & UserName & _
"\Desktop\Consolidated.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
oWbname2 = ActiveWorkbook.Name
sDSheet = ActiveSheet.Name
nCountDestination = 1
Workbooks(oWbname).Activate
For Each oSheet In Workbooks(oWbname).Worksheets
oSheet.Activate
sDSheet = ActiveSheet.Name
ActiveSheet.UsedRange.Copy
For Each oRange In ActiveSheet.UsedRange
nCountCol = oRange.Column
Next
Workbooks(oWbname2).Activate
Cells(nCountDestination, 1).PasteSpecial xlPasteAll
nCount = nCountDestination
For Each oRange In ActiveSheet.UsedRange
nCountDestination = oRange.Row + 1
Next
Range(Cells(nCount, nCountCol + 1), _
Cells(nCountDestination - 1, nCountCol + 1)).Value = oSheet.Name
Workbooks(oWbname).Activate
With ActiveWorkbook.Sheets(sDSheet).Tab
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0
End With
Next
Workbooks(oWbname2).Save: Workbooks(oWbname).Close False
MsgBox "File with consolidated data from workbook " & Chr(10) & _
"[ " & oWbname & " ] saved on your desktop!"
End Sub

Related

VBA Export Excel to CSV with Range

I used the code that I found here.
After some changes this is the code I have now:
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim Item As String
Dim Path As String
Dim CurrentWB As Workbook, TempWB As Workbook
Path = "F:\Excels\csv export\"
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.Worksheets("Nieuw Artikelnummer").UsedRange.Copy
Item = Range("D2")
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.Worksheets("csv").UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
MyFileName = Path & "\" & Item & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
MsgBox ".csv file has been created: " _
& vbCrLf _
& MyFileName
End Sub
The problem I have is that it uses the UsedRange, but I would like to select the Range that is copied into the new .csv file.
What can I do to select the Range to copy into the new file instead of the UsedRange?
This will open an input box on the article number sheet that allows you to hand select or type in a range:
Sub ExportAsCSV()
Dim MyFileName As String
Dim Item As String
Dim Path As String
Dim CurrentWB As Workbook, TempWB As Workbook
Dim myrangeNA As Range
Dim myRangeCSV As Range
Path = "F:\Excels\csv export\"
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.Worksheets("Nieuw Artikelnummer").Activate
Set myrangeNA = Application.InputBox(prompt:="Select a range to copy", Type:=8)
Item = Range("D2")
Set TempWB = Application.Workbooks.Add(1)
myrangeNA.Copy Destination:=TempWB.Worksheets("Sheet1").Range("A1")
MyFileName = Path & "\" & Item & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
MsgBox ".csv file has been created: " _
& vbCrLf _
& MyFileName
End Sub
If you don't want to select it, change the myrangeNA to whatever range you want, like range("A5:C20") and it should work.
For situations like this, I prefer to isolate the actions to a standalone Sub or Function that I can call with parameters. In this way I can reuse it as needed, either in this project or another one.
So I've separated the actions of copying the selected data range and pasting to a temporary workbook, then saving to a CSV file in it's own Function. The action returns a True/False result as a check for success.
Option Explicit
Sub test()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim destCSVfile As String
destCSVfile = "C:\Temp\" & ws.Range("D2")
If ExportAsCSV(Selection, destCSVfile) Then
MsgBox ".csv file has been created: " _
& vbCrLf _
& destCSVfile
Else
MsgBox ".csv file NOT created"
End If
End Sub
Private Function ExportAsCSV(ByRef dataArea As Range, _
ByVal myFileName As String) As Boolean
'--- make sure we have a range to export...
ExportAsCSV = False
If dataArea Is Nothing Then
Exit Function
End If
dataArea.Copy
'--- create a temporary workbook that will be saved as a CSV format
Dim tempWB As Workbook
Set tempWB = Application.Workbooks.Add(1)
With tempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
'--- suppress alerts to convert the temp book to CSV
Application.DisplayAlerts = False
tempWB.SaveAs filename:=myFileName, FileFormat:=xlCSV, _
CreateBackup:=False, Local:=True
tempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
ExportAsCSV = True
End Function
Your other two questions in the comment above mention pasting transposed values, which you would do by changing the line myrangeNA.Copy Destination:=TempWB.Worksheets("Sheet1").Range("A1") to
myrangeNA.Copy
TempWB.Worksheets("Sheet1").Range("A1").PasteSpecial _
Paste:=xlPasteValues, Transpose:=True
This site is a great reference source for all the various objects and methods and properties in the Office VBA collection: https://learn.microsoft.com/en-us/office/vba/api/overview/excel/object-model
(or https://learn.microsoft.com/de-de/office/vba/api/overview/excel/object-model if you prefer to have about five words translated to German)

Excel VBA open & save as

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

when Relative path of input file Included in script Error reported -VBA

I have this macro which is taking input excel, and generating excel report and copying it. Below code works fine when i am running manually from excel with msg dialog box, however when i tried to pass relative path of input file, i am getting "Runtime Error 9"-Subscript out of range. While debugger points to Each sh as error context.
How do I fix this?
Sub buildSCTR()
'
' Merge CSV and built pivot for SCTR
' Ver 0.1
' 5-July-2017 P. Coffey
'
Const FILELIMIT = 0 'used to hardcode number of files will work with. better ways exist but this will do for now
Dim firstFilename As String
Dim secondFilename As String
Dim outputFilename As String
Dim element As Variant
Dim dirLocation As String
Dim macroWb As Object
Dim lastrow As Integer
Dim samName As String
Dim RootFolder As String
'code allows for multiple import, but using it for one one import here
Dim filenameArr(0 To FILELIMIT) As Variant 'so can push cells into it later
Dim inputSelected As Variant 'has to variant to iterate over via for each even though its a string
Set macroWb = ThisWorkbook
RootFolder = ActiveWorkbook.Path
'get new csv to load
'Set fd = Application.FileDialog(msoFileDialogFilePicker)
' With fd
' .AllowMultiSelect = True
' .Title = "Pick SC file to load"
'.Filters.Clear
'.Filters.Add "csv", "*.csv*"
'If .Show = True Then
' i = 0
' For Each inputSelected In .SelectedItems
' filenameArr(i) = Dir(inputSelected) 'kludgy....
' dirLocation = Split(inputSelected, filenameArr(i))(0)
' i = i + 1
'Next inputSelected
' Else
' MsgBox ("Nothing selected")
' Exit Sub
' End If
'End With
Application.StatusBar = "Starting to update"
element = RootFolder + "/Output/_SCT_Details_With_Comments.csv"
' For Each element In filenameArr()
If Not IsEmpty(element) Then 'as hardcoded length of array have to do this
Workbooks.Open (element)
Call CopyWorkbook(CStr(element), macroWb.Name)
'close csv as done with it
Workbooks(element).Close SaveChanges:=False
End If
'Next element
'convert to table
samName = ActiveSheet.Range("A2").Value
ActiveSheet.Name = samName & "_SCT_Data"
'assumes col A is contiguous
lastrow = ActiveSheet.Range("A1").End(xlDown).Row
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A1:$U" & lastrow), , xlYes).Name = "SCT"
'build pivot
Dim objWs As Worksheet
Dim objPT As PivotTable
Dim objPC As PivotCache
Sheets.Add.Name = "Summary"
Set objWs = ActiveSheet
Set objPC = ActiveWorkbook.PivotCaches.Create(xlDatabase, "SCT")
Set objPT = objPC.CreatePivotTable(objWs.Range("A3"), TableName:="SCTR")
With ActiveSheet.PivotTables("SCTR").PivotFields("Target_SC")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("SCTR").PivotFields("Action")
.Orientation = xlRowField
End With
ActiveSheet.PivotTables("SCTR").AddDataField ActiveSheet.PivotTables( _
"SCTR").PivotFields("PNI_SC"), "Count of PNI_SC", xlCount
'have to do it in this order else vba was removing pni_sc from row field...who knows why
With ActiveSheet.PivotTables("SCTR").PivotFields("PNI_SC")
.Orientation = xlRowField
.Position = 1
End With
'--update sheet with last sync info
macroWb.Sheets("Summary").Range("A1").Value = samName
macroWb.Sheets("Summary").Range("A3").NumberFormat = "h:mm dd/mm"
'save as new file
Dim timestamp As String
timestamp = Format(Now(), "mmddhh")
ActiveWorkbook.SaveAs Filename:= _
dirLocation & samName & "_SCTR_" & timestamp & ".xlsm" _
, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
'exit msg
Application.StatusBar = False
Application.ScreenUpdating = True
MsgBox ("Completed - saved file as " & dirLocation & samName & "_SCTR_" & timestamp & ".xlsm")
End Sub
Sub CopyWorkbook(source As String, target As String)
'copy all sheets from one workbook to another
Dim sh As Worksheet, wb As Workbook
Set wb = Workbooks(target)
For Each sh In Workbooks(source).Worksheets
sh.Copy After:=wb.Sheets(wb.Sheets.Count)
Next sh
End Sub
the problem is due to the fact that the source contains the fullname of the workbook (path included) and Excel expects only the shortname of the workbook (without the path)
so adapt the call instruction like this
Call CopyWorkbook(ActiveWorkbook.Name, macroWb.Name)

Issue with VBA code when combining csv files as a workbook with separate sheets

I am having an issue with my code. I want to:
Combine multiple .csv files into 1 workbook with each .csv file as a separate sheet;
Shorten the sheet names(since they are too long with extra metadata;
Add a new sheet with the sheet names as hyperlinks to the sheets;
save the file as xlsx.
My problem is that when I step through the code or run it via alt+F8 it works fine, but when I use the shortcut it doesn't do anything but open the first .csv file. The macro is in the personal.xlsb location.
I am sure I could simplify my code so any suggestions are very welcome. Here is my code:
Sub CombineCsvFilesWithShortSheetLinks()
'ctrl+Shift+b
'Will ask you to open CSV files you wish to combine
Dim myDir As String, fn As String, wb As Workbook
Set wb = ActiveWorkbook
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show Then myDir = .SelectedItems(1) & "\"
End With
Application.ScreenUpdating = False
If myDir = "" Then Exit Sub
fn = Dir(myDir & "*.csv")
Do While fn <> ""
With Workbooks.Open(myDir & fn)
.ActiveSheet.Copy after:=wb.Sheets(wb.Sheets.Count)
.Close False
End With
fn = Dir
Loop
'save as
Dim workbook_Name As Variant
workbook_Name = Application.GetSaveAsFilename
If workbook_Name <> False Then
ActiveWorkbook.SaveAs _
Filename:=workbook_Name ', _
'FileFormat:=52(-4143 xlWorkbookNormal =Excel workbook file format.) 'I had issues with this line because it would just same a extensionless file, so my work around was to just type .xlsx at the end of my file name
End If
'List WS Name Rename Add Hyperlink
'Will shorten the sheet names and add a new sheet with a list of hyperlinks to each sheet
'list old names
Dim xWs As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
xTitleId = "sheetnames"
Application.Sheets(xTitleId).Delete
Sheets("Sheet1").Select
Set xWs = Application.ActiveSheet
xWs.Name = xTitleId
For i = 2 To Application.Sheets.Count
xWs.Range("A" & (i - 1)) = Application.Sheets(i).Name
Next
Application.DisplayAlerts = True
'list new names'
selectworksheet = "sheetnames"
Range("B1").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-1],21,12)"
ActiveCell.Select
Selection.AutoFill Destination:=ActiveCell.Range("A1:A11")
ActiveCell.Range("A1:A11").Select
'rename'
selectworksheet = "sheetnames"
For i = 1 To 12
On Error Resume Next
oldname = Cells(i, 1).Value
newname = Cells(i, 2).Value
Sheets(oldname).Name = newname
Next
'create hyperlink page that Creates Links To All Sheets
Range("C1").Select
Dim cell As Range
For Each xWs In ActiveWorkbook.Worksheets
If ActiveSheet.Name <> xWs.Name Then
ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
"'" & xWs.Name & "'" & "!A1", TextToDisplay:=xWs.Name
ActiveCell.Offset(1, 0).Select
End If
Next xWs
'save_workbook
ActiveWorkbook.Save
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.