Save clipboard when closing workbook VBA - excel

It seems like a easy question, yet I can't seem to find the correct answer on Google.
What I want to do is open a workbook, copy a section and then close the workbook while saving the section I just copied.
I'm aware of the function to disable the clipboard prompt:
Application.CutCopyMode = False
ActiveWindow.Close
But this does not save the clipboard. Thus far I have written the following code to do so:
Sub Input()
Application.ScreenUpdating = False
Dim wb As Workbook
Dim wbPad As String
On Error GoTo ErrHandler
wbPad = ThisWorkbook.Sheets("Voorblad").Range("C10").Value
Set wb = Workbooks.Open(wbPad)
Cells.Select
Selection.Copy
Windows("Masterfile.xlsm").Activate
Worksheets("INPUT").Activate
Cells.Select
ActiveSheet.Paste
Range("A1").Select
Worksheets("Voorblad").Activate
Exit Sub
ErrHandler:
MsgBox ("Bestand niet gevonden. Controleer de maand en de naam van het bestand dat je wilt openen")
End Sub
If this is not possible, I would like to .Activate the workbook I opened using the cell reference and close this.

Maybe you could just skip the whole .select and .activate commands and use the optional Destination parameter of the .copy function.
(https://learn.microsoft.com/de-de/office/vba/api/excel.range.copy)

Since you did not provide how you want to save the range, I've added multiple basic examples below.
OPT1 - Save as .xlsx or .csv
Dim cpyRng As Range, newWb As Workbook, sPath As String
Application.DisplayAlerts = False 'remove system alert prompts
Set cpyRng = ThisWorkbook.Sheets("Sheet1").Range("A1:C10") 'Change sheet and range as needed
sPath = ThisWorkbook.Path & "\"
Set newWb = Workbooks.Add
With newWb
cpyRng.Copy
.Sheets("Sheet1").Cells(1, 1).PasteSpecial Paste:=xlPasteValues
.SaveAs Filename:=sPath & "Test" & "_" & Format(Date, "yyyymmdd") & ".xlsx", FileFormat:=51 'change file name to suit
'If you want to save as .csv use
'.SaveAs Filename:=sPath & "Test" & "_" & Format(Date, "yyyymmdd") & ".csv", FileFormat:=6
.Close
End With
'save your workbook and quit Excel
ThisWorkbook.Save = False 'use "True" if you want to save changes
Application.Quit
Application.DisplayAlerts = True 'Turn system alert prompts back on(best practice)
OPT2 - Save as .pdf
Dim cpyRng As Range, sPath As String
Application.DisplayAlerts = False 'remove system alert prompts
Set cpyRng = ThisWorkbook.Sheets("Sheet1").Range("A1:C10") 'Change sheet and range as needed
sPath = ThisWorkbook.Path & "\"
'Change file name to suit
cpyRng.ExportAsFixedFormat Type:=xlTypePDF, Filename:=sPath & "Test" & "_" & Format(Date, "yyyymmdd") & _
".pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
Application.DisplayAlerts = True 'Turn system alert prompts back on(best practice)
OPT3 - Save as Word Doc
Dim cpyRng As Range
Set cpyRng = ThisWorkbook.Sheets("Sheet1").Range("A1:C10") 'Change sheet and range as needed
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
cpyRng.Copy
With objWord
.Visible = True
.Documents.Add
.Selection.Paste
End With
Application.CutCopyMode = False
Set objWord = Nothing

Related

Export csv separated by columns

I have an Excel with several sheets I want to export to csv delimited by columns.
When I run the code, it exports the files to csv but comma delimited, not column delimited as I export in csv.
Any help would be appreciated.
Sub SaveShtsAsBook()
Dim Sheet As Worksheet, SheetName$, MyFilePath$, N&
MyFilePath$ = ActiveWorkbook.path & "\" & _
Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 5)
With Application
.ScreenUpdating = False
.DisplayAlerts = False
' End With
On Error Resume Next '<< a folder exists
MkDir (MyFilePath & "_csv") '<< create a folder
For N = 1 To Sheets.Count
Sheets(N).Activate
SheetName = ActiveSheet.Name
Cells.Copy
Workbooks.Add (xlWBATWorksheet)
With ActiveWorkbook
With .ActiveSheet
.Paste
.Name = SheetName
[A1].Select
End With
'save book in this folder
.SaveAs ThisWorkbook.path & "\_csv\" & SheetName & ".csv", FileFormat:=xlCSV
.Close SaveChanges:=True
End With
.CutCopyMode = False
Next
End With
Sheet1.Activate
End Sub
Thanks!
Edit: Screenshot that clarifies my problem.
https://imgur.com/a/mPn997B
Define FileFormat as xlText and the file will be TAB delimited, which you obviously are looking for.
f.ex.:
Private Sub CommandButton1_Click()
Dim wb As Workbook
Set wb = ActiveWorkbook
wb.SaveAs "c:\tmp\tabtest.csv", xlText
End Sub

Save each worksheet with formatting in loop

I have a template file and 4 source documents that I use to fill the template. For each row in sheet2, I create a new blank template and fill it out, resulting in somewhere between 10-100 files. I want to save these in a loop, but having issues with Excel force closing on me. This is my code so far, recycled from a different project.
Dim w As Long, wb As Workbook
Dim fp As String, fn As String
Dim folderName As String
Dim fsoFSO
On Error GoTo bm_Safe_Exit
'Application.ScreenUpdating = False 'stop screen flashing
Application.DisplayAlerts = False 'stop confirmation alerts
'start with a reference to ThisWorkbook
With ThisWorkbook
folderName = Format(Date, "ddmmyyyy")
'set path to save
'fp = "<PATH HERE>" & folderName
fp = "C:\Users\Username\OneDrive - CompanyName\Documents\Projects\ThisProject\csvOutput\" & folderName
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
If fsoFSO.FolderExists(fp) Then
MsgBox "FOLDER - " & fp & " ALREADY EXISTS, DELETE CONTENTS TO PROCEED"
Exit Sub
Else
fsoFSO.CreateFolder (fp)
End If
'cycle through each of the worksheets
For w = 6 To Worksheets.Count
With Worksheets(w)
.Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
With ActiveWorkbook
fn = .Worksheets(1).Name
Cells.Select
Selection.SpecialCells(xlCellTypeVisible).Copy
Worksheets.Add after:=Sheets(Sheets.Count)
Range("A1").Select
ActiveSheet.Paste
Worksheets(1).Delete
Worksheets(1).Name = fn
.SaveAs Filename:=fp & Chr(92) & fn, FileFormat:=51
.Close savechanges:=False '<~~ already saved in line above
End With
End With
Next w
End With
bm_Safe_Exit:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub ```
The code below worked for me: not sure exactly where the problem might vbe with your posted code, but within your With blocks not everything is scope to the block using a leading .
Sub Test()
Dim w As Long, wb As Workbook, wbNew As Workbook
Dim fp As String, fn As String
Dim fsoFSO
On Error GoTo bm_Safe_Exit
Set wb = ThisWorkbook
fp = "C:\Users\Username\OneDrive - CompanyName\Documents\Projects\" & _
"ThisProject\csvOutput\" & Format(Date, "ddmmyyyy") & "\"
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
If fsoFSO.FolderExists(fp) Then
MsgBox "FOLDER - " & fp & " ALREADY EXISTS, DELETE CONTENTS TO PROCEED"
Exit Sub
Else
fsoFSO.CreateFolder fp
End If
'cycle through each of the worksheets
For w = 6 To wb.Worksheets.Count
'explicitly create a new single-sheet workbook as the destination
Set wbNew = Workbooks.Add(Template:=xlWBATWorksheet)
wb.Worksheets(w).Copy before:=wbNew.Sheets(1)
DeleteSheet wbNew.Sheets(2)
With wbNew
fn = .Worksheets(1).Name
.Worksheets.Add after:=.Worksheets(.Worksheets.Count)
.Worksheets(1).Cells.SpecialCells(xlCellTypeVisible).Copy _
Destination:=.Worksheets(2).Range("A1")
DeleteSheet .Worksheets(1)
.Worksheets(1).Name = fn
.SaveAs Filename:=fp & fn, FileFormat:=51
.Close savechanges:=False '<~~ already saved in line above
End With
Next w
Exit Sub
bm_Safe_Exit:
MsgBox Err.Description
End Sub
'utility sub
Sub DeleteSheet(ws As Worksheet)
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End Sub

Why does loop stop after exporting only one file?

I am trying to export Excel files to another folder as PDFs. The macro is stored in a separate .xlsm that I have open, and I directed the code to the folder with all the files that need to be PDFs.
The code only exports the first PDF in the folder. The error I got was that it could not operate in Page Break Mode, so I set it to normal mode for running the code but I still get the error.
Beyond that, it is reading the workbook that I have the macro stored in as a second active window. I ran the code to export to PDF on a single PDF and it worked as expected.
Option Explicit
Sub PPG_PDF_File()
'Below is used to make code run faster
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim wkbDest As Workbook
Dim wkbSource As Workbook
Set wkbDest = ThisWorkbook
Dim strExtension As String
Dim wsA As Worksheet
Dim strName As String
Dim strName1 As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Const strPath1 As String = "C:\Users\steve.argen\Documents\PPG\GW Sampling March 2020\PPG Balogna NUMBER 2\Final excel sheets\Test Macro Folder DNAPL Wells\"
ChDir strPath1
strExtension = Dir(strPath1 & "*.xls*")
Do While strExtension <> ""
Set wkbSource = Workbooks.Open(strPath1 & strExtension)
With wkbSource.Sheets("LowFlow GW front")
ActiveWindow.View = xlNormalView
On Error GoTo errHandler
Set wkbSource = ActiveWorkbook
Set wsA = ActiveSheet
'get active workbook folder, if saved
strPath = wkbSource.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = wsA.Range("A1").Value _
& " - " & wsA.Range("A2").Value _
& " - " & wsA.Range("A3").Value
'create default name for savng file
strFile = wkbSource.Name & ".pdf"
strFile = Replace(strFile, ".xlsx", "")
strPathFile = "C:\Users\steve.argen\Documents\PPG\GW Sampling March 2020\PPG Balogna NUMBER 2\Final excel sheets\Final PDF\" & strFile
'export to PDF in current folder
wkbSource.Sheets(Array("LowFlow GW Front", "LowFlow GW Back")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
strPathFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
Application.CutCopyMode = False 'If you ever need to copy a large amount of info, this will hide any warnings
ActiveWindow.View = xlPageBreakPreview
End With
wkbSource.Close savechanges:=False
strExtension = Dir
Loop
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
This code
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
it should be at the end of the routine and not in the middle of the loop.

Paste Special Method of Range class failed error while trying to save worksheet

I'm trying to copy a worksheet data and save it in a new worksheet without copying the underlying formulas from the original sheet(shtAnalysis). I'm unable to do that as I'm getting error:
Paste Special Method of Range class failed
at the line
wsPaste.UsedRange.PasteSpecial xlPasteValues.
Public Sub PrepareFileAttachment()
Application.CalculateFull
Dim wrkBook As Workbook, wsPaste As Worksheet
Dim Path As String
Set wrkBook = Workbooks.Add
Set wsPaste = wrkBook.Worksheets(1)
Path = "C:\RandomPath" & "\" & "Report" & Format(Now, "mmddyyyy")
shtAnalysis.Copy
wsPaste.Activate
wsPaste.UsedRange.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ActiveWorkbook.SaveAs filename:=Path, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
shtControl.Range(GENERATED_FILENAME).Value = Path & ".xlsx"
ActiveWindow.Close
End Sub
Avoid the Activate and the Used.Range, thus, change these lines:
shtAnalysis.Copy
wsPaste.Activate
wsPaste.UsedRange.PasteSpecial xlPasteValues
To these:
shtAnalysis.Copy
wsPaste.PasteSpecial xlPasteValues
The original code is trying to copy the whole worksheet shtAnalysis, but is allowed to paste it only in the UsedRange, which is something that VBA does not like.
Please give this a try
Public Sub PrepareFileAttachment()
Application.CalculateFull
Dim wrkBook As Workbook, wsPaste As Worksheet
Dim openedWorkbook As Workbook
Dim Path As String
Set openedWorkbook = ThisWorkbook
Set wrkBook = Workbooks.Add
Set wsPaste = wrkBook.Worksheets(1)
Path = "C:\RandomPath" & "\" & "Report" & Format(Now, "mmddyyyy")
openedWorkbook.Sheets("shtAnalysis").Copy
wsPaste.Activate
wsPaste.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ActiveWorkbook.SaveAs Filename:=Path, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
shtControl.Range(GENERATED_FILENAME).Value = Path & ".xlsx"
ActiveWindow.Close
End Sub

How to iterate through worksheets and AutoFilter by one column

I am working on a macro that copies each sheet and saves it as a separate workbook, but at some point in the macro I need to clear a couple cells in row Z and then filter column Z to remove zeros. I am very new to VBA so please excuse the ugly code.
The macro I have will work to separate and save the files, but I keep getting error 1004: Application-defined or object-defined error.
I have been searching for other posts for hours and still can't figure it out. Any help is appreciated.
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim sh As Worksheet
Set sh = Sheets("Table of Contents")
Dim DateString As String
Dim FolderName As String
Dim filterRow As Integer
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
Set Sourcewb = ActiveWorkbook
Set sh = ActiveSheet
'Create new folder to save the new files in
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = Sourcewb.Path & "\" & "Department Expenses - Split"
MkDir FolderName
'Copy every visible sheet to a new workbook
For Each sh In Sourcewb.Worksheets
filterRow = sh.Range("Z" & Rows.Count).End(x1Up).Row 'This is the line giving me problems
ActiveSheet.Next.Select
Range("Z9").Select
Selection.ClearContents
Range("Z12").Select
Selection.ClearContents
Range("Z14").Select
Selection.ClearContents
Range("Z77").Select
Selection.ClearContents
Range("Z100").Select
Selection.ClearContents
sh.Range(filterRow).AutoFilter Field:=26, Criteria1:="<>0"
You can try something like this first open the workbook in the folder you want to copy the sheets and than do the edit and filter after save each worksheet in the same folder where you open the workbook. You were getting the error because you were not qualifying Rows.Count needs to be sh.Rows.Count so it know from what sheet it's counting.
Sub CopySheetsToNewWorkbook()
Dim xPath As String
Dim xWs As Worksheet
Dim filterRow As Integer
Dim questionBoxPopUp As VbMsgBoxResult
questionBoxPopUp = MsgBox("Are you sure you want to copy each worksheets as a new workbook in the current folder?", vbQuestion + vbYesNo + vbDefaultButton1, "Copy Worksheets?")
If questionBoxPopUp = vbNo Then Exit Sub
On Error GoTo ErrorHandler
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each sh In Sourcewb.Worksheets
filterRow = sh.Range("Z" & sh.Rows.Count).End(xlUp).Row 'not too sure why you need this
ActiveSheet.Next.Select
Range("Z9").Select
Selection.ClearContents
Range("Z12").Select
Selection.ClearContents
Range("Z14").Select
Selection.ClearContents
Range("Z77").Select
Selection.ClearContents
Range("Z100").Select
Selection.ClearContents
sh.Range("Z" & filterRow).AutoFilter Field:=26, Criteria1:="<>0" 'Change column "Z" to suit your needs. I think you need jut the header range to filter it.
For Each xWs In ActiveWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs filename:=xPath & "\" & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next xWs
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Process completed!", vbInformation
Exit Sub '<--- exit here if no error occured
ErrorHandler:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Debug.Print Err.Number; Err.Description
MsgBox "Sorry, an error occured." & vbNewLine & vbNewLine & vbCrLf & Err.Number & " " & Err.Description, vbCritical, "Error!"
End Sub

Resources