i have an issue with this code. I need to save the data from a workbook to a new workbook but the new workbook doesn't save, I do it manually. I need it to save automatically. Any idea what is going on?
this is my code so far
Private Sub CommandButton3_Click()
Dim wb As Workbook
Dim wb_New As Workbook
Set wb = ThisWorkbook
Dim wbstring As String
Dim input_file_name As String
input_file_name = InputBox("Enter file name", "Enter new workbook file name")
wbstring = "C:\PIME\\"
Workbooks.Add.SaveAs Filename:=wbstring & input_file_name & ".xls", FileFormat:=56
Set wb_New = ActiveWorkbook
wb_New.Worksheets("Sheet1").Range("A1:I2000").Value = wb.Worksheets("NUMB").Range("A1:I2000").Value
End Sub
You got it almost right - Set wb_New to the new workbook, populate the data then use SaveAs method.
Set wb_New = Workbooks.Add
wb_New.Worksheets("Sheet1").Range("A1:I2000").Value = wb.Worksheets("NUMB").Range("A1:I2000").Value
wb_New.SaveAs Filename:=wbstring & input_file_name & ".xls", FileFormat:=56
Copy a Range to a New One-Worksheet Workbook
The only mistake I could find was that you need to remove one of the two trailing backslashes from the path:
wbstring = "C:\PIME\"
An Improvement
Option Explicit
Private Sub CommandButton3_Click()
' Source
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Worksheets("NUMB")
' Destination
Dim dFolderPath As String: dFolderPath = "C:\PIME\"
If Right(dFolderPath, 1) <> "\" Then dFolderPath = dFolderPath & "\"
Dim dExtension As String: dExtension = ".xls"
If Left(dExtension, 1) <> "." Then dExtension = "." & dExtension
If Len(Dir(dFolderPath, vbDirectory)) = 0 Then
MsgBox "The path '" & dFolderPath & "' doesn't exist.", vbCritical
Exit Sub
End If
Dim dFileName As String
dFileName = InputBox("Enter file name", "Enter new workbook file name")
If Len(dFileName) = 0 Then
MsgBox "Canceled or no entry."
Exit Sub
End If
Dim dwb As Workbook: Set dwb = Workbooks.Add(xlWBATWorksheet) ' single...
Dim dws As Worksheet: Set dws = dwb.Worksheets(1) ' ... worksheet,...
' ... in another language it may not be 'Sheet1'.
' Copy by Assignement (the most efficient way to copy only values)
dws.Range("A1:I2000").Value = sws.Range("A1:I2000").Value
' Save(As)
Dim dFilePath As String: dFilePath = dFolderPath & dFileName & dExtension
Dim ErrNum As Long
Application.DisplayAlerts = False ' overwrite without confirmation
On Error Resume Next
dwb.SaveAs Filename:=dFilePath, FileFormat:=xlExcel8 ' or 56
ErrNum = Err.Number
On Error GoTo 0
Application.DisplayAlerts = True
' Close
dwb.Close SaveChanges:=False
' Inform
If ErrNum = 0 Then
MsgBox "File saved.", vbInformation
Else
MsgBox "Could not save the file.", vbCritical
End If
End Sub
You may tweak your code as below...
Workbooks.Add.SaveAs Filename:=wbstring & input_file_name & ".xls", FileFormat:=56
Set wb_New = ActiveWorkbook
wb_New.Worksheets("Sheet1").Range("A1:I2000").Value = wb.Worksheets("NUMB").Range("A1:I2000").Value
'Then either use wbNew.Save or wbNew.Close True as per your need
wbNew.Save 'To save the work and leave the new workbook open
'OR
wbNew.Close True 'To save the work and close the new workbook.
Related
I have a workbook with filtered ranges on each sheet. I have tried a couple different methods but when stepping through it only does the first sheet or none at all. This is what I have tried.
dim ws as worksheet
For Each Ws In ThisWorkbook.Worksheets
If Ws.AutoFilterMode Then
Ws.AutoFilter.ShowAllData
End If
Next Ws
this one isn't doing anything at all
this one is less sophisticated and not what I want.
For Each ws In ThisWorkbook.Worksheets
Rows("1:1").Select
Selection.AutoFilter
Next ws
this is only doing the first worksheet and not moving to the next.
this is the full code and it is not returning any errors
Sub Cleanup()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim mergedWb As Workbook
Set mergedWb = Workbooks.Add()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Application.ScreenUpdating = False
FolderPath = "<folder path>"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True)
For Each Sheet In wb.Sheets
Sheet.Copy After:=mergedWb.Sheets(1)
Next Sheet
wb.Close
Filename = Dir()
Loop
Sheets(1).Delete
For Each ws In ThisWorkbook.Worksheets
If ws.AutoFilterMode Then
ws.AutoFilter.ShowAllData
End If
Next ws
End Sub
Copy Sheets to New Workbook
Issues
ThisWorkbook is the workbook containing this code. It has nothing to do with the code so far: you're adding a new (destination) workbook (mergedWb) and you're opening (source) files ('wb') whose sheets (Sheet) will be copied. Instead, you should use:
For Each ws In mergedWb.Worksheets
When you use the Sheets collection, you need to keep in mind that it also includes charts. Therefore, you should declare:
Dim Sheet As Object
You need to qualify the first destination (work)sheet to ensure the correct worksheet is deleted:
Application.DisplayAlerts = False ' delete without confirmation
mergedWb.Sheets(1).Delete
Application.DisplayAlerts = True
To turn off the auto filter, you need to use:
dws.AutoFilterMode = False
You can avoid the loop by copying all sheets (that are not very hidden) at once (per workbook):
swb.Sheets.Copy After...
The line swb.Sheets.Copy (no arguments) copies all sheets (that are not very hidden) to a new workbook.
The Code
Option Explicit
Sub Cleanup()
Const SOURCE_FOLDER_PATH As String = "C:\Test"
Const SOURCE_FILE_PATTERN As String = "*.xls*"
If Not CreateObject("Scripting.FileSystemObject") _
.FolderExists(SOURCE_FOLDER_PATH) Then
MsgBox "The folder '" & SOURCE_FOLDER_PATH & "' doesn't exist.", _
vbCritical
Exit Sub
End If
Dim sFolderPath As String: sFolderPath = SOURCE_FOLDER_PATH
If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"
Dim sFileName As String: sFileName = Dir(sFolderPath & SOURCE_FILE_PATTERN)
If Len(sFileName) = 0 Then
MsgBox "No files found."
Exit Sub
End If
Dim swb As Workbook
Dim dwb As Workbook
Dim sFilePath As String
Dim IsNotFirstSourceWorkbook As Boolean
Application.ScreenUpdating = False
Do While Len(sFileName) > 0
sFilePath = sFolderPath & sFileName
Set swb = Workbooks.Open(Filename:=sFilePath, ReadOnly:=True)
If IsNotFirstSourceWorkbook Then
swb.Sheets.Copy After:=dwb.Sheets(dwb.Sheets.Count)
Else
swb.Sheets.Copy ' creates a new workbook containing the sheets
Set dwb = Workbooks(Workbooks.Count)
IsNotFirstSourceWorkbook = True
End If
swb.Close SaveChanges:=False
sFileName = Dir()
Loop
Dim dws As Worksheet
For Each dws In dwb.Worksheets
If dws.AutoFilterMode Then dws.AutoFilterMode = False
Next dws
' Decide what to do with the new workbook e.g.:
' Application.DisplayAlerts = False ' overwrite without confirmation
' dwb.SaveAs sFolderPath & "CleanUp " & Format(Date, "yyyymmdd")
' Application.DisplayAlerts = True
' dwb.Close SaveChanges:=False ' it has just been saved
Application.ScreenUpdating = True
MsgBox "Cleaned up.", vbInformation
End Sub
I am using this code which exports activesheet to CSV. However, I am looking to modify this so I can pass as arguments the names of multiple sheets to export.
Sometimes it could be 2 sheets, sometimes it could be 10 sheets and I want to somehow define the names of the sheets as parameters for the export.
Sub saveSheetToCSV()
Dim myCSVFileName As String
Dim tempWB As Workbook
Application.DisplayAlerts = False
On Error GoTo err
myCSVFileName = ThisWorkbook.Path & "\" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
ThisWorkbook.Sheets("YourSheetToCopy").Activate
ActiveSheet.Copy
Set tempWB = ActiveWorkbook
With tempWB
.SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
err:
Application.DisplayAlerts = True
End Sub
Export Worksheet to New Workbook
!!! denotes places to be checked carefully and possibly modified.
Option Explicit
Sub ExportWorksheetsTEST()
Dim wb As Workbook: Set wb = Workbooks.Open("C:\Test\Test.xlsx")
ExportWorksheets "Sheet1", "Sheet5", "Sheet8"
End Sub
Sub ExportWorksheets(ParamArray WorkSheetNames() As Variant)
Dim dFolderPath As String: dFolderPath = ThisWorkbook.Path & "\"
Const dFileExtension As String = ".csv"
Const dDateFormat As String = "dd-MMM-yyyy hh-mm"
Const dFileNameDelimiter As String = "-"
' This is the requirement.
' The recommendation is to put it as the first parameter of the procedure:
' Sub ExportWorksheets(ByVal wb As Workbook, ParamArray...)!!!
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim dDateString As String: dDateString = VBA.Format(VBA.Now, dDateFormat)
Dim ws As Worksheet
Dim n As Long
Dim dFilePath As String
For n = LBound(WorkSheetNames) To UBound(WorkSheetNames)
On Error Resume Next ' prevent error if worksheet doesn't exist
Set ws = wb.Worksheets(WorkSheetNames(n))
On Error GoTo 0
If Not ws Is Nothing Then
' Build the file path!!!
dFilePath = dFolderPath & ws.Name & dFileNameDelimiter _
& dDateString & dFileExtension
ws.Copy ' copy to a new workbook
With Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite w/o confirmation
.SaveAs Filename:=dFilePath, FileFormat:=xlCSV
Application.DisplayAlerts = True
.Close SaveChanges:=False
End With
Set ws = Nothing
End If
Next n
MsgBox "Worksheets exported.", vbInformation
End Sub
I currently import sheets of data into excel that I am exporting from CAD. This includes summaries, counts and other data. I would like to add to the code so that it will import a file from a predetermined directory C:\Jobs\packlist and using a number inside a cell ='PL CALC'!B1 (this will determine the file name). The idea being to remove the open dialog box and increase automation.
This is what I have found that works so far. It opens a selected file and copies it into the workbook after sheet 18.
'import excel data sheet
Sub import()
Dim fName As String, wb As Workbook
'where to look for the framecad excel file
ChDrive "C:"
ChDir "C:\Jobs\packlist"
fName = Application.GetOpenFilename("Excel Files (*.xl*), *.xl*")
Set wb = Workbooks.Open(fName)
For Each sh In wb.Sheets
Sheets.Copy After:=ThisWorkbook.Sheets(18)
Exit For
Next
wb.Close False
Worksheets("PL CALC").Activate
End Sub
Import Sheets
Option Explicit
Sub ImportSheets()
Const ProcTitle As String = "Import Sheets"
Const sFolderPath As String = "C:\Jobs\packlist\"
Const sfnAddress As String = "B1"
Const sFileExtensionPattern As String = ".xls*"
Const dwsName As String = "PL CALC"
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = dwb.Worksheets(dwsName)
Dim sFilePattern As String: sFilePattern = sFolderPath & "*" _
& dws.Range(sfnAddress).Value & sFileExtensionPattern
Dim sFileName As String: sFileName = Dir(sFilePattern)
If Len(sFileName) = 0 Then
MsgBox "No file found..." & vbLf & "'" & sFilePattern & "'", _
vbCritical, ProcTitle
Exit Sub
End If
Application.ScreenUpdating = False
Dim swb As Workbook: Set swb = Workbooks.Open(sFolderPath & sFileName)
Dim sh As Object
For Each sh In swb.Sheets
sh.Copy After:=dwb.Sheets(dwb.Sheets.Count)
Next sh
swb.Close SaveChanges:=False
dws.Activate
'dwb.Save
Application.ScreenUpdating = True
MsgBox "Sheets imported.", vbInformation, ProcTitle
End Sub
I am currently using following code to save an Excel workbook. Instead of saving complete work book, I just wish to save a sheet in this workbook named Reconciliation. All values in the sheet should be saved as values while keeping the formatting the same.
Sub Button3_Click()
' Yes
' Code to save consumer wise mirs on the desktop
Dim Path As String
Dim filename As String
On Error GoTo Err_Clear
Path = Environ("USERPROFILE") & "\Desktop\rohailnisar\"
filename = Range("A1")
ActiveWorkbook.SaveAs filename:=Path & filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Err_Clear:
If Err <> 0 Then
MkDir CreateObject("wscript.shell").specialfolders("desktop") & "\rohailnisar"
Path = Environ("USERPROFILE") & "\Desktop\rohailnisar\"
filename = Range("A1")
ActiveWorkbook.SaveAs filename:=Path & filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
End If
End Sub
Export a Worksheet
This saves a copy of a worksheet as the only sheet in a new workbook in the same folder. Before saving, it converts formulas to values. It is saved in the .xlsx format 'removing' any code.
If the code is in the open (initial) workbook, then replace ActiveWorkbook with ThisWorkbook.
Option Explicit
Sub SaveWorksheet()
On Error GoTo ClearError
Dim swb As Workbook: Set swb = ActiveWorkbook
Dim sws As Worksheet: Set sws = swb.Worksheets("Reconciliation")
Dim FolderPath As String: FolderPath = swb.Path & Application.PathSeparator
Dim BaseName As String: BaseName = sws.Range("E1").Value
Dim FilePath As String: FilePath = FolderPath & BaseName & ".xlsx"
sws.Copy
Dim dwb As Workbook: Set dwb = Workbooks(Workbooks.Count)
dwb.Worksheets(1).UsedRange.Value = dwb.Worksheets(1).UsedRange.Value
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs Filename:=FilePath, FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
'dwb.Close
ProcExit:
Exit Sub
ClearError:
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
Resume ProcExit
End Sub
Instead of saving complete work book, I just wish to save a sheet in this workbook named Reconciliation. All values in the sheet should be saved as values while keeping the formatting the same.
Code
Dim wbThis As Workbook
Dim wsThis As Worksheet
Dim wbThat As Workbook
Dim wsThat As Worksheet
'~~> Change this to the workbook which has the Reconciliation sheet
Set wbThis = ThisWorkbook
Set wsThis = wbThis.Sheets("Reconciliation")
'~~> This will create a new workbook with only Reconciliation
wsThis.Copy
'~~> Get that object. It will be last in the queue
Set wbThat = Workbooks(Workbooks.Count)
Set wsThat = wbThat.Sheets("Reconciliation")
'~~> Convert to values
wsThat.UsedRange.Value = wsThat.UsedRange.Value
'~~> Save that workbook
wbThat.SaveAs Filename:=Path & Filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
I have a function that basically makes a copy of the current file, and save it to users' "Downloads" folder.
However, while the SaveAs works, the output does not contain any modules. Instead, they are all linked to the exporting file.
Sub PushToProduction()
Application.ScreenUpdating = False
' save a copy of current file to the Downloads folder
outputPath = Environ$("USERPROFILE") & "\Downloads\"
d = Format(Date, "yyyymmdd")
fileName = outputPath & "REDACTED " & d & " v1.00.xlsm"
' prepare to save a copy of the file without the last tab
sheetCount = Application.Sheets.Count - 1
Dim tabs() As String
ReDim tabs(1 To sheetCount)
For i = 1 To sheetCount
tabs(i) = Worksheets(i).Name
Next
Worksheets(tabs).Copy
ActiveWorkbook.SaveAs fileName, XlFileFormat.xlOpenXMLWorkbookMacroEnabled
ActiveWorkbook.Close False
Application.CutCopyMode = False
Application.ScreenUpdating = True
MsgBox ("Success!")
End Sub
The output does not even have the "Modules" folder.
Is there anyway to solve this?
Create a Workbook Copy and Modify It
Option Explicit
Sub PushToProduction()
Dim dFolderPath As String
dFolderPath = Environ$("USERPROFILE") & "\Downloads\"
Dim d As String: d = Format(Date, "yyyymmdd")
Dim dFilePath As String
dFilePath = dFolderPath & "REDACTED " & d & " v1.00.xlsm"
Application.ScreenUpdating = False
' Create a reference to the Source Workbook ('swb').
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
' Save a copy of the Source Workbook.
If StrComp(dFilePath, swb.FullName, vbTextCompare) = 0 Then
MsgBox "You are trying save a copy of the file to the same location.", _
vbCritical, "Push to Production"
Exit Sub
End If
swb.SaveCopyAs dFilePath
' Open the copy, the Destination Workbook ('dwb'), remove its last sheet
' and close saving the changes.
Dim dwb As Workbook: Set dwb = Workbooks.Open(dFilePath)
Application.DisplayAlerts = False
dwb.Sheets(dwb.Sheets.Count).Delete
Application.DisplayAlerts = True
dwb.Close SaveChanges:=True
Application.ScreenUpdating = True
' Inform.
MsgBox "Success!", vbInformation, "Push to Production"
' Explore Destination Folder.
'swb.FollowHyperlink dFolderPath
End Sub