Macro to revert changes since save - vba

I found an old script online to close the document without saving the changes, then re-open the document:
Sub RevertFile()
wkname = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
ActiveWorkbook.Close Savechanges:=False
Workbooks.Open Filename:=wkname
End Sub
I want this since you can't "undo" changes caused by running a macro. However, it does not seem to work in MS Office v1609. Firstly, the document does not re-open after it is closed. Secondly, the modifications are saved when I want them not to be. How can I rewrite this script to get it to work? Thanks.
[edit]
Here is the other sub-routine I am using.
Sub FixPlatforms()
'PURPOSE: Find & Replace a list of text/values throughout entire workbook
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim sht As Worksheet
Dim platList As Variant
Dim x As Long
platList = Array _
( _
"PS4", "PlayStation 4", _
"PS3", "PlayStation 3", _
"PS2", "PlayStation 2", _
"PSV", "PlayStation Vita", _
"PSP", "PlayStation Portable", _
"WIN", "Microsoft Windows", _
"SNES", "Super Nintendo Entertainment System" _
)
'Loop through each item in Array lists
For x = 1 To UBound(platList) Step 2
'Loop through each worksheet in ActiveWorkbook
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace What:=platList(x), Replacement:=platList(x - 1), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
Next x
End Sub
Is there something wrong with it?

You shouldn't have to close the workbook in any event. Attempting to open a workbook that is already open produces the following.
Adding application.displayalerts = false should be sufficient to avoid that confirmation.
Option Explicit
Sub RevertFile()
Dim wkname As String
wkname = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
Application.DisplayAlerts = False
Workbooks.Open Filename:=wkname
Application.DisplayAlerts = True
End Sub

Related

Converting workbook in PDF without blank pages

Hiii
I wrote a code to export sheets from one workbook to an other workbook and then convert it in pdf, but I have a lot of blank pages (maybe because of hidden formula or I don't know.
If you have any idea for what to add to my code in order to have a decent file it would be very appreciated.
Workbooks.Open FileName:="C:\Users\User\Documents\Tests Salome\dailypdf.xlsx"
Dim wbto2 As Workbook: Set wbto2 = Workbooks("dailypdf.xlsx")
wb.Activate
For Each sht In Sheets
If sht.Name <> "USD" And sht.Name <> "Balance" Then
Else
sht.Copy Before:=wbto2.Sheets(wbto2.Sheets.Count)
Rows("140:351").EntireRow.Delete '(I tried to delete the hidden rows)
End If
Debug.Print sht.Name
Next
wbto2.Activate
Application.DisplayAlerts = False
Sheets("Sheet1").Delete
Application.DisplayAlerts = True
FileName = Create_PDF(Source:=wbto2, _
FixedFilePathName:=iFile, _
OverwriteIfFileExist:=True, _
OpenPDFAfterPublish:=False)
The code functions but the result does not satisfy me because of the blank pages..
you can try any option below
1.Delete all unwanted rows before saving as PDF.
2.Set Print area
3.try to save excel range as PDF directly
'Enter Worksheet name, range Address, PDF file path and name
Sheets("Sheet Name").Range("A1:D50").ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Temp\PDF_name.pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True

VBA "Application-defined or Object-defined error" when protect a worksheet

I'm writing a VBA macro that protects another workbook when user clicks a button and open it via current workbook. I got "Application-defined or Object-defined error". I looked into this post and made sure that the workbook that needs to be opened is unprotected. But the error still occurs. Please help. Thanks!
Sub LockModelParInput()
Dim wbk As Workbook
Workbooks.Open (ModelParVarClusLocalPath & "\" & ProN & "_ModelParameter_UserInput.xlsx")
Set wbk = Workbooks(ProN & "_ModelParameter_UserInput.xlsx")
wbk.Activate
With ActiveWorkbook.Worksheets("Model_Rule")
.Protection.AllowEditRanges.Add Title:="VIF Cut Off Level 2", _
Range:=Range("C4") *'error occurs on this line*
.Protection.AllowEditRanges.Add Title:="p_value stay", Range:= _
Range("D4")
.Protection.AllowEditRanges.Add Title:="Trend Threshold", Range _
:=Range("E4")
.Protection.AllowEditRanges.Add Title:="r_var_ks_penalize", Range _
:=Range("B10")
.Protection.AllowEditRanges.Add Title:="fast backward", Range:= _
Range("C16")
.Protection.AllowEditRanges.Add Title:="locked forward", Range:= _
Range("C17")
.Protection.AllowEditRanges.Add Title:="enhanced stepwise", Range _
:=Range("C18")
.Protection.AllowEditRanges.Add Title:="traditional backward", _
Range:=Range("C19")
.Protection.AllowEditRanges.Add Title:="sas stepwise", Range:= _
Range("C21")
.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
End With
End Sub
You need to check to see if the edit range's title has already been used - they can't be duplicated. Just knock up a quick function like this to iterate them:
Private Function EditRangeExists(Sh As Worksheet, Title As String) As Boolean
With Sh.Protection
Dim found As AllowEditRange
For Each found In .AllowEditRanges
If found.Title = Title Then
EditRangeExists = True
Exit Function
End If
Next
End With
End Function
...then check to make sure you're not attempting to add duplicates. I'd use a small wrapper for the test to make your code cleaner:
Private Sub TryAddProtectionRange(Title As String, Target As Range)
With Target
If EditRangeExists(Target.Parent, Title) Then
Exit Sub
End If
.Parent.Protection.AllowEditRanges.Add Title, Target
End With
End Sub
Then you can use it like this:
Sub LockModelParInput()
Dim wbk As Workbook
Set wbk = Workbooks.Open(ModelParVarClusLocalPath & "\" & ProN & _
"_ModelParameter_UserInput.xlsx")
Dim Sh As Worksheet
Set Sh = wbk.Worksheets("Model_Rule")
With Sh
TryAddProtectionRange "VIF Cut Off Level 2", .Range("C4")
TryAddProtectionRange "p_value stay", .Range("D4")
'Etc.
.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
End With
End Sub
I'd add some sort of error handling and/or have TryAddProtectionRange return a Boolean for success also.

Ungroup Sheets from an array in VBA

I've been trying to get an easy printout (in PDF using a single button) of one sheet with only active range and one chart located in another sheet. I've got everything working, except after I print, both sheets are grouped together and I can't edit my chart.
I'm trying to make this foolproof and easy for coworkers during real time operations. Right now I can right-click and select 'Ungroup sheets' to fix it, but I hate to have to do that each time (or explain that it needs to be done).
I tried to select a sheet, a different sheet, only one sheet etc. I can't figure out how to get VBA to ungroup the sheets at the end. Any ideas?
Sub CustomPrint()
'if statement to ask for file path
If Dir(Environ("commonprogramfiles") & "\Microsoft Shared\OFFICE" _
& Format(Val(Application.Version), "00") & "\EXP_PDF.DLL") <> "" Then
If FixedFilePathName = "" Then
'Open the GetSaveAsFilename dialog to enter a file name for the PDF file.
FileFormatstr = "PDF Files (*.pdf), *.pdf"
fname = Application.GetSaveAsFilename("", filefilter:=FileFormatstr, _
Title:="Create PDF")
'If you cancel this dialog, exit the function.
If fname = False Then Exit Sub
Else
fname = FixedFilePathName
End If
'Dynamic reference to RT drilling data
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Dim sht As Worksheet
Set sht = Worksheets("rt drilling data")
Set StartCell = Range("A1")
'Refresh UsedRange
Worksheets("rt drilling data").UsedRange
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'Select Range
sht.Range("A1:K" & LastRow).Select
Sheets("Chart Update").Activate
ActiveSheet.ChartObjects(1).Select
ThisWorkbook.Sheets(Array("chart update", "RT drilling data")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=fname, IgnorePrintAreas:=False
'If the export is successful, return the file name.
If Dir(fname) <> "" Then RDB_Create_PDF = fname
End If
If OverwriteIfFileExist = False Then
If Dir(fname) <> "" Then Exit Sub
End If
On Error GoTo 0
Worksheets("ws model updates").Select
End Sub
If Dir(fname) <> "" Then Exit Sub will bypass Worksheets("ws model updates").Select
If OverwriteIfFileExist = False Then
If Dir(fname) <> "" Then
Worksheets("ws model updates").Select
Exit Sub
End If
End If

Object required error. saving ActiveSheet to new workbook

The purpose of this macro is to select each item in a drop down data validation list, update the sheet and then save the sheet as a new workbook. I get the error "Object required" for the block of code after ws.SaveAs. Can anyone see the problem, as I cannot :/
Sub Create_excel_sheets()
Dim strValidationRange As String
Dim rngValidation As Range
Dim rngDepartment As Range
Dim ws As Worksheet
strValidationRange = Range("AD5").Validation.Formula1
Set rngValidation = Range(strValidationRange)
For Each rngDepartment In rngValidation.Cells
Range("AD5").Value = rngDepartment.Value
ActiveSheet.Calculate
Set ws = ActiveSheet
ws.SaveAs _
FileFormat:=52, _
Filename:="C:\Test\" & rngDepartment.Value.xlsx, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
End Sub
It seems that you are using the parameters for a Worksheet.ExportAsFixedFormat Method inside a Worksheet.SaveAs method.
Additionally, the filename:= string concatenation is a little wonky with & rngDepartment.Value.xlsx. Best to simply leave off the file extension and allow the FileFormat:= parameter to supply the correct one. In this case, the XlFileFormat Enumeration you chose (e.g. 52) is for xlOpenXMLWorkbookMacroEnabled but you seem to be trying to append .xlsx on the end.
ws.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
Filename:="C:\Test\" & rngDepartment.Value '<~~no extension
I'm not sure if you were trying to go with .SaveAs or .ExportAsFixedFormat. I've chosen a simple .SaveAs for demonstration

Rebuild a workbook with VBA

I am trying to run the below VBA that I found online. The purpose of the code is to copy the data from all of the worksheets in a workbook to a different workbook. A couple key points:
1) I am trying to copy the data in all worksheets NOT the actual worksheets to the new workbook
2) The macro does a lot: makes sure you have a back-up file; creates a new worksheet (TargetWorkbook) and saves with the source workbook's name; etc. however, the most important part (and where I believe it is erroring) is copying the worksheets
3) I understand what is going on with the code but not savvy enough to make it work.
Sub Update_SmartView_Workbook()
' Copies sheets from a source workbook to new and current Excel target workbook to
' get rid of the "2003 or earlier backbone" that interferes with SmartView.
' Keyboard Shortcut: Ctrl+z
' Copyleft 2013 By MJ Henderson. No rights reserved. Free and worth every penny.
' User assumes all risk. No warranties implied or otherwise.
Dim ConfirmBackup As Integer
Dim SourceWorkbook, TargetWorkbook As Workbook
Dim SourceWorksheet As Worksheet
Dim SourceWorkbookName As String
' User must make a backup before proceeding.
ConfirmBackup = MsgBox("Have you made a backup copy of the source file?", vbYesNo, "Confirm Backup")
If ConfirmBackup = vbNo Then
MsgBox "Try again when you have a backup copy of the source file", vbOKOnly, "Backup Required"
Exit Sub
End If
' Find and open the source file
Application.FindFile
Set SourceWorkbook = ActiveWorkbook
SourceWorkbookName = ActiveWorkbook.Name
SourceWorkbookDirectoryPath = Left(ActiveWorkbook.FullName, Len(ActiveWorkbook.FullName) - Len(SourceWorkbookName))
' Create a new target workbook in the same folder as the source workbook
Workbooks.Add
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx", _
FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=True
' Copy each worksheet in SourceWorkbook to TargetWorkbook THIS IS WHERE THE FIX IS NEEDED
SourceWorkbook.Activate
For Each SourceWorksheet In SourceWorkbook.Worksheets
SourceWorksheet.Cells.Copy
Windows("TargetWorkbook.xlsx").Activate
ActiveWindow.WindowState = xlNormal
On Error Resume Next
TargetWorkbook.Sheets(SourceWorksheet.Name).Delete
Range("A1").Select
ActiveSheet.Paste
Range("A1").Select
ActiveSheet.Name = SourceWorksheet.Name
Application.CutCopyMode = cancel
Next
' Close SourceWorkbook, rename SourceWorkbook with suffix "_OLD"
SourceWorkbook.Activate
SourceWorkbook.Saved = True
SourceWorkbook.Close SaveChanges:=False
Name SourceWorkbookDirectoryPath & SourceWorkbookName As SourceWorkbookDirectoryPath & SourceWorkbookName & "_OLD"
' Global replace to remove any references to old workbook. (Fixes interbook links.)
Cells.Replace What:="[" & SourceWorkbookName & "]", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
' Rename TargetWorkbook as SourceWorkbook's original name, delete TargetWorkbook
TargetWorkbook.Activate
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & SourceWorkbookName, _
FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Saved = True
ActiveWorkbook.Close SaveChanges:=False
Kill SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx"
End Sub
I believe these lines are driving the error:
Windows("TargetWorkbook.xlsx").Activate
ActiveWindow.WindowState = xlNormal
The error I am getting is "Run Time Error 9 - Subscript out of Range"
Any idea on how to fix?
Use Workbooks("TargetWorkbook.xlsx").Activate instead of Windows...
I would recommend to eliminate the activating if the sheet and workbooks; we do not need it. Just referencing the object is enough.
This is an untested code see how it goes you might need to change it a little bit to fit your needs.
Option Explicit
Sub Test()
Dim ConfirmBackup As Integer
Dim SourceWorkbook, TargetWorkbook As Workbook
Dim SourceWorksheet As Worksheet
Dim SourceWorkbookName As String
Dim SourceWorkbookDirectoryPath As String
' User must make a backup before proceeding.
ConfirmBackup = MsgBox("Have you made a backup copy of the source file?", vbYesNo, "Confirm Backup")
If ConfirmBackup = vbNo Then
MsgBox "Try again when you have a backup copy of the source file", vbOKOnly, "Backup Required"
Exit Sub
End If
' Find and open the source file
Application.FindFile
Set SourceWorkbook = ActiveWorkbook
SourceWorkbookName = ActiveWorkbook.Name
SourceWorkbookDirectoryPath = Left(ActiveWorkbook.FullName, Len(ActiveWorkbook.FullName) - Len(SourceWorkbookName))
' Create a new target workbook in the same folder as the source workbook
Workbooks.Add
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx", _
FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=True
' Copy each worksheet in SourceWorkbook to TargetWorkbook THIS IS WHERE THE FIX IS NEEDED
For Each SourceWorksheet In SourceWorkbook.Worksheets
TargetWorkbook.Sheets(SourceWorksheet.Name).Delete
SourceWorksheet.Copy After:=TargetWorkbook.Sheets(TargetWorkbook.Sheets.Count)
Next
' Close SourceWorkbook, rename SourceWorkbook with suffix "_OLD"
SourceWorkbook.Close SaveChanges:=True
Name SourceWorkbookDirectoryPath & SourceWorkbookName As SourceWorkbookDirectoryPath & SourceWorkbookName & "_OLD"
' Global replace to remove any references to old workbook. (Fixes interbook links.)
Cells.Replace What:="[" & SourceWorkbookName & "]", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
' Rename TargetWorkbook as SourceWorkbook's original name, delete TargetWorkbook
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & SourceWorkbookName, _
FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close SaveChanges:=True
Kill SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx"
End Sub
I hope it helps