Create workbook and copy sheets with values only - excel

Sub values_dump()
Dim sourceWB As Workbook
Dim destWB As Workbook
Dim ws As Worksheet
Dim path As String
Dim fname As String
Application.ScreenUpdating = False
path = ThisWorkbook.path & "\_bck\"
fname = "values_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsm"
Set sourceWB = ThisWorkbook
Set destWB = Workbooks.Add
destWB.SaveAs path & fname
For Each ws In sourceWB.Worksheets
Workbooks(sourceWB).Sheets(ws).Copy after:=Workbooks(destWB).Sheets(1)
Next ws
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
I am getting an error on this line destWB.SaveAs path & fname - it says that I cannot use the ".xlsm" extension ?
In addition I would like to copy the sheets to the new workbook but only retain the values and original formatting.
My code, erroneously copies all the formulae. I do not want to destruct in any way the original workbook.

You are arbitrarily tacking on a Macro-Enabled Workbook file extension (e.g. xlsm) but using Workbook.SaveAs method with the default FileFormat paramter (found in Excel Options ► Save ► Save files in this format:. In fact, it would be better to leave off the .xlsm altogether and specify the desired file format. Excel will add .xlsm if you pick the correct format. See xlFileFormat enumeration for a full list of available SaveAs file types.
If you want to revert the formulas to their values, simply make a copy of the worksheet then use .Cells = .Cells.Value.
Sub values_dump()
Dim sourceWB As Workbook
Dim destWB As Workbook
Dim ws As Worksheet
Dim path As String
Dim fname As String
Dim c As long
Application.ScreenUpdating = False
path = ThisWorkbook.path & "\_bck\"
fname = "values_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsm"
Set sourceWB = ThisWorkbook
Set destWB = Workbooks.Add
destWB.SaveAs Filename:=path & fname, FileFormat:=xlOpenXMLWorkbookMacroEnabled 'Open XML Workbook Macro Enabled (52)
For Each ws In sourceWB.Worksheets
if ws.autofiltermode then ws.autofiltermode = false
ws.Copy after:=destWB.Sheets(1)
With destWB.Sheets(2).usedrange
for c = 1 to .columns.count
.columns(c).Cells = .columns(c).Cells.Value
next c
End With
destWB.save
Next ws
Application.ScreenUpdating = True
End Sub
When you Set a workbook-type var to a Workbook Object, you can use the var directly. You seemed to be using it like it was the Workbook.Name property. The same goes for the Worksheet Object and the Worksheet .Name property.

Related

Save a sheet instead of a complete workbook

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

How to export xls files to txt files reading them from folder (Visual Basic)?

I am trying to read files *.xls from u:\test folder. There is one sheet in every file. I want to copy cell B1 and to paste it into new file to A1. Then I want to copy range B1:B57 and to paste it into the new file/sheet to B1:B57. Then I want to copy range K1:U57 and copy (the values only) to the new file/sheet C1 location. I am doing this in Visual Basic 6 and I have problem to find out how to use the range function... I tried to activated and select the sheet(1). Then I wanted to use the command Set SrchRange = ActiveSheet.Range(Cells(2, 1)). I got error 1004 Application defined or object defined error. Here on this line. If I would successed to select/copy/paste the cell areas to new file/sheet, then I would like to save the current file as txt, given the .txt extenssion. How to correct this code to reach the goal?
Sub FromExcelToNpad()
'export activesheet as txt file
Dim my_files As String
Dim folder_path As String
Dim wb As Workbook, NewWB As Workbook
Dim ws As Worksheet
Dim SrcRange As Range
folder_path = "u:\test"
my_files = Dir(folder_path & "\*.xls", vbDirectory)
Do While my_files <> vbNullString
Set wb = Workbooks.Open(folder_path & "\" & my_files)
Set ws = wb.Sheets(1)
Set NewWB = Workbooks.Add
ws.Activate
ws.Select
Set SrchRange = ActiveSheet.Range(Cells(2, 1))
wb.ActiveSheet.UsedRange.Copy NewWB.Sheets(1).Range("A1")
wb.Close True
Application.DisplayAlerts = True
my_files = Dir()
Loop
End Sub
Update
The range and cells are copied:
Dim my_files As String
Dim folder_path As String
Dim wb As Workbook, NewWB As Workbook
Dim ws As Worksheet
folder_path = "u:\test"
my_files = Dir(folder_path & "\*.xls", vbDirectory)
Do While my_files <> vbNullString
Set wb = Workbooks.Open(folder_path & "\" & my_files)
Set ws = wb.Sheets(1)
Set NewWB = Workbooks.Add
ws.Range("B1").Copy NewWB.Sheets(1).Range("A1")
ws.Range("B3:B57").Copy NewWB.Sheets(1).Range("A3:A57")
ws.Range("K1:U57").Copy
NewWB.Sheets(1).Range("B1:L57").PasteSpecial xlValues
wb.Close True
With NewWB
Application.DisplayAlerts = False
.SaveAs Filename:=folder_path & "\" & my_files, FileFormat:=xlText
.Close True
Application.DisplayAlerts = True
End With
wb.Save
my_files = Dir()
Loop
I am trying to save the file as .txt . I have error Run time error - automation error. Also there is a dialog asking me if I want to save data from a "page". How to turn this off?

Merge specific workbooks into one

Sub MergeWorkbooks()
Dim Path As String
Dim FileName As String
Dim ws As Worksheet
Dim wb As Workbook
Application.EnableEvents = False
Application.ScreenUpdating = False
Path = "C:\Users\Name\Documents\Data\"
FileName = Dir(Path & "\*.xls", vbNormal)
Do Until FileName = ""
Set wb = Workbooks.Open(FileName:=Path & "\" & FileName)
For Each ws In wb.Worksheets
ws.Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count)
Next ws
wb.Close False
FileName = Dir()
Loop
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
I have 2 workbooks in same directory. Workbook 1 contain sheet A only and Workbook 2 contains sheets B and C. How can I merge sheet A and sheet C to my current workbook?
Make sure you open your source workbooks and then use the Worksheet.Move method or the Worksheet.Copy method to move or copy them into your current workbook.
Dim SourceWb1 As Workbook
Set SourceWb1 = Workbooks.Open(FileName:="C:\Path\To\Your\workbook1.xls")
SourceWb1.Worksheets("Sheet A").Move After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
Dim SourceWb2 As Workbook
Set SourceWb2 = Workbooks.Open(FileName:="C:\Path\To\Your\workbook2.xls")
SourceWb2.Worksheets("Sheet C").Move After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
If you used the .Move method make sure you don't forget to save your source workbooks:
SourceWb1.Close SaveChanges:=True
SourceWb2.Close SaveChanges:=True
If you used the .Copy method close them without saving:
SourceWb1.Close SaveChanges:=False
SourceWb2.Close SaveChanges:=False

Copying multiple sheets and renaming the worksheet

I want to copy multiple sheets from one workbook(4 out of 14) but i'm starting with one("Data"). I want to rename the workbook based on a cell in the first workbook. with this code I get an "run-time error '1004' Excel cannot access the file 'C:\3B4DD....
my code so far:
Sub Newyeartest()
sheetstocopy = "data"
Worksheets(sheetstocopy).Copy
Dim FName As String
Dim FPath As String
FPath = "C:"
FName = Sheets("data").Range("A1") & ".xlsm"
ThisWorkbook.SaveAs Filename:=FPath & "\" & FName, FileFormat:=52
End sub
If I delete the "Fileformat:=52" It seems to go better but I get a text that this file must be saved as an macro enabled file. But I would guess that "Xlsm" is macro enabled?
Instead of copying worksheets, the better way is to copy the workbook with all the worksheets and then delete the ones that are not needed.
The code saves the workbook first, using the path of the current workbook;
Then it starts checking every worksheet, making sure that the name is not "data";
If the name is not "data" and there are more than 1 worksheets left, it deletes the worksheet;
The Application.DisplayAlerts = False is needed, in order to remove the msgbox for confirmation of the deletion of the worksheet. Then the Alerts are back set to True;
If the name is not "data" and this is the last worksheet, it gives a MsgBox "Last worksheet cannot be deleted!", as far as a workbook should always have at least 1 worksheet, by design;
Sub NewTest()
ThisWorkbook.SaveAs ThisWorkbook.Path & "\new.xlsm"
Dim sheetToCopy As String: sheetToCopy = "data"
Dim wks As Worksheet
For Each wks In ThisWorkbook.Worksheets
If wks.Name <> sheetToCopy Then
If ThisWorkbook.Worksheets.Count > 1 Then
Application.DisplayAlerts = False
ThisWorkbook.Worksheets(wks.Name).Delete
Application.DisplayAlerts = True
Else
MsgBox "Last worksheet cannot be deleted!"
End If
End If
Next wks
End Sub
This should do the trick:
Option Explicit
Sub Newyeartest()
Dim wb As Workbook
Dim SheetNames As Variant, Key As Variant
Dim FName As String, FPath As String
Application.ScreenUpdating = False
SheetNames = Array("data", "data2", "data3", "data4") 'store the sheet names you want to copy
Set wb = Workbooks.Add 'set a workbook variable which will create a new workbook
'loop through the sheets you previously stored to copy them
For Each Key In SheetNames
ThisWorkbook.Sheets(Key).Copy After:=wb.Sheets(wb.Sheets.Count)
Next Key
'delete the first sheet on the new created workbook
Application.DisplayAlerts = False
wb.Sheets(1).Delete
FPath = "C:\Test"
FName = ThisWorkbook.Sheets("data").Range("A1") & ".xlsm"
wb.SaveAs Filename:=FPath & "\" & FName, FileFormat:=52
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
You cannot save directly to C:\ so you need to create a folder and the code will work.

Trying to copy a table to csv file and name it using original file name

I'm new to VBA and stuck on an issue. I'm trying to copy a table to a .csv file and I want the end result to contain the original .xlsm name & the table name and date/time. I've successfully pieced together code to export the table to .csv with the table name and date/time but I'm struggling to get the file mane in there. I get the following error "Method 'SaveAs' of object'_Workbook' failed"
Below is what I have, any help would be great!
Sub ExportTableBanquetEarnings()
Application.ScreenUpdating = False
Sheets("BanquetEarnings").Visible = True
Sheets("BanquetEarnings").Select
Dim wb As Workbook, wbNew As Workbook
Dim ws As Worksheet, wsNew As Worksheet
Dim wbNewName As String
Dim wbCurrent As String
wbCurrent = ThisWorkbook.FullName
Set wb = ThisWorkbook
Set ws = ActiveSheet
Set wbNew = Workbooks.Add
With wbNew
Set wsNew = wbNew.Sheets("Sheet1")
wbNewName = ws.ListObjects(1).Name
ws.ListObjects(1).Range.Copy
wsNew.Range("A1").PasteSpecial Paste:=xlPasteAll
.SaveAs Filename:="F:\admin\Report Databases\BanquetTipouts" & "\" &
wbCurrent & wbNewName & Format(Now, "yyyymmdd_hhmm") & ".csv", _
FileFormat:=xlCSVMSDOS, CreateBackup:=False
End With
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
ActiveWorkbook.RefreshAll
Sheets("BanquetEarnings").Visible = False
Sheets("Blank Cost Sheet").Select
Workbooks.Open "F:\Function Agreements\Cost Sheets M\Payroll Report -
V2.xlsm"
End Sub
The below code will show the path of that Workbook
wbCurrent = ThisWorkbook.FullName
I think what you meant to use is...
wbCurrent = ThisWorkbook.Name
Also, I think another issue might be the Now method, it should be as Now()

Resources