Disable clipboard prompt in Excel VBA on workbook close - vba

I have an Excel workbook, which using VBA code that opens another workbook, copies some data into the original, then closes the second workbook.
When I close the second workbook (using Application.Close), I get a prompt for:
Do you want to save the clipboard.
Is there a command in VBA which will bypass this prompt?

I can offer two options
Direct copy
Based on your description I'm guessing you are doing something like
Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy
ThisWorkbook.Sheets("SomeSheet").Paste
wb2.close
If this is the case, you don't need to copy via the clipboard. This method copies from source to destination directly. No data in clipboard = no prompt
Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy ThisWorkbook.Sheets("SomeSheet").Cells(<YourCell")
wb2.close
Suppress prompt
You can prevent all alert pop-ups by setting
Application.DisplayAlerts = False
[Edit]
To copy values only: don't use copy/paste at all
Dim rSrc As Range
Dim rDst As Range
Set rSrc = wb2.Sheets("YourSheet").Range("YourRange")
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
rDst = rSrc.Value

If I may add one more solution: you can simply cancel the clipboard with this command:
Application.CutCopyMode = False

I have hit this problem in the past - from the look of it if you don't actually need the clipboard at the point that you exit, so you can use the same simple solution I had. Just clear the clipboard. :)
ActiveCell.Copy

If you don't want to save any changes and don't want that Save prompt while saving an Excel file using Macro then this piece of code may helpful for you
Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub
Because the Saved property is set to True, Excel responds as though the workbook has already been saved and no changes have occurred since that last save, so no Save prompt.

There is a simple work around. The alert only comes up when you have a large amount of data in your clipboard. Just copy a random cell before you close the workbook and it won't show up anymore!

Just clear the clipboard before closing.
Application.CutCopyMode=False
ActiveWindow.Close

proposed solution edit works if you replace the row
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
with
Set rDst = ThisWorkbook.Sheets("SomeSheet").Range("YourRange").Resize(rSrc.Rows.Count, rSrc.Columns.Count)

Related

VBA deleting a duplicate copy of chart object fails in Excel 2013

I have a VBA code that is intended to copy the contents of a range into a chart, to be able to export it to a PNG file (+some post-processing using an external command). Here is the relevant part:
Sub GenererImage() ' Entry point
getparams ' Collect parameters and define global variables
MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen,Format:=xlPicture
Application.DisplayAlerts = False
With ObjetGraphique.Duplicate
.Chart.Paste
.Chart.Export Filename:=CheminImage, Filtername:="PNG"
.Select
.Delete
End With
Application.DisplayAlerts = True
End Sub
The getparams procedure called in there is just collecting some parameters from another worksheet to define:
"MiseEnPage": reference to the worksheet object where the range I want to copy exists,
"ZoneImage" is set to the "B4:F11" string (refers to the range address),
"ObjetGraphique" is a reference to a ChartObject inside the "MiseEnPage" sheet. This ChartObject is an empty container (I am mainly using it to easily set the width and height).
"CheminImage" is a string containing the path to the picture filename on disk.
This code used to work perfectly in Excel 2010. Now my company has deployed Excel 2013 and my code now fails on the .Delete line, leaving the copy of the ChartObject (with the range picture pasted inside it) on the sheet and stopping macro execution.
I have tried activating the worksheet first, selecting the duplicate prior to deleting it and other things, to no avail. When tracing the execution in the debugger it chokes on the delete line with error 1004.
I am frustratingly stuck. Any clue?
If this works
With ObjetGraphique.Duplicate
.Chart.Paste
.Chart.Export Filename:=CheminImage, Filtername:="PNG"
.Select
End With
Selection.Delete
we have to assume that either the With is holding a reference and preventing the delete, or that the delete routine called by the selection object is not the same delete that's called by ObjetGraphique.Duplicate.delete, or that it's a subtle timing bug and that the extra time it takes to retrieve the selected object is enough to fix it.
OK after fiddling a lot with the object model, here is (the relevant part of) my final solution. Many thanks to HarassedDad for the clues.
Sub GenererImage() ' Point d'entrée
getparams
MiseEnPage.Range(ZoneImage).CopyPicture Appearance:=xlScreen, Format:=xlPicture
Application.DisplayAlerts = False
With ObjetGraphique
.Chart.Paste
.Chart.Export filename:=CheminImage, Filtername:="PNG"
.Chart.Shapes(1).Delete
End With
Application.DisplayAlerts = True
End Sub
What seems to happen is that the .Paste method of the Chart object creates a Shape in the .Shapes collection of this object. I can delete this Shape, but not the Chart itself or the ChartObject. Excel 2010 would allow that, but not Excel 2013.
I still do not understand the reasons, but at least I have something that works (until the next excel update probably...).

Excel - copy from another workbook with conditional formatting intact

I've figured out most of this myself, but the part that is hanging me up is being able to paste the conditional formatting.
I want to be able to have a workbook open, run a VBA script to open another workbook, copy a range from it, then paste that to the original workbook.
The most success I've had is recording the macro and make this happen:
With the original, target workbook open...
Open the source workbook
Copy range A1:X105
Close source workbook
Paste into worksheet titled "Temp" in target workbook
The problem is that the source workbook contains conditional formatting, and if the source workbook is closed before you paste into the target workbook, the conditional formatting isn't being pasted.
So either I need to find a way to paste the data with the conditional formatting, or I need to be able to switch back to the target workbook before closing the source workbook. This is a process that is going to need to be ran multiple times with different target workbooks, so the VBA code can't refer to a workbook filename for the target. The source workbook will always have the same path though.
Searching the site, I could only find solutions that specified the path for both workbooks.
This is what I have right now:
Sub CopyData()
Application.DisplayAlerts = False
Workbooks.Open filename:="source.xlsx", _
UpdateLinks:=3
Range("A1:X105").Select
Selection.Copy
ActiveWindow.Close
Sheets("Temp").Select
ActiveSheet.Paste
Application.DisplayAlerts = True
End Sub
I suppose what I need to implement into this is to declare the target workbook as a variable. Can someone help with that?
You can just dim the workbook and then copy and paste. After you have completed that you can then using the variable, close the workbook. Code would be as follows:
Sub CopyData()
Application.DisplayAlerts = False
Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy
ThisWorkbook.ActiveSheet.Selection.Paste
wbSource.Close
Application.DisplayAlerts = True
End Sub
I don't see how you determine what range you paste on the target workbook but will leave that for another question. The answer by Emily Alden I don't think will work because you can't copy from a source that is closed. Clipboard behaves differently with Excel than with other applications.
Based on new information:
Sub CopyData()
Application.DisplayAlerts = False
Workbooks.Open filename:="source.xlsx", _
UpdateLinks:=3
Range("A1:X105").Select
Selection.Copy
ActiveWindow.Close
Sheets("Temp").Select
ActiveSheet.PasteSpecial xlPasteFormats
Application.DisplayAlerts = True
End Sub
Previous:
From:Copy conditional formatting from one cell to another using VBA?
Sub test()
Sheets("B").[B1].Copy: Sheets("A").[A1:A10].PasteSpecial xlPasteFormats
End Sub
Is a code that will paste the conditional formatting.
Mostly what you need to do is change the order:
Open Source using a Prompt for the User to select file
Copy Range from Source
Paste Range to Original
Close Source

VBA - Workbook Macro Pass Error

I have created an Excel file containing about 5 pages of vba code. All was good until,I choosen to create a macro for the workbook for its protection. Something like.
Dim pass as string/
if pass <> "PAR> or pass<>"par" then activeworkbook.close.
I think that the OR messes the things up. Now I can't access my workbook. Whatever pass I introduced it closes the workbook. I may mention here that pass is an inputbox.
Can someone help me in resolving this problem. I've lost my entire work.
LE: i've made it! Thank you for your support! :)
Try this way:
Sub main()
Dim secAutomation As MsoAutomationSecurity
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Remember the macro security settings and disable macros in target workbook. '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
secAutomation = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Workbooks.Open "<path to your workbook>"
''''''''''''''''''''''''''''''''''''''''''''''
'Reinstate previous macro security settings. '
''''''''''''''''''''''''''''''''''''''''''''''
Application.AutomationSecurity = secAutomation
End Sub
or manually change your Macro settings to 'Disable all macros with notification'
open any other workbook and get to the VBA IDE (ALT+F11)
type in Immediate Window
application.EnableEvents=False
then you can open your "impossible" workbook
as soon as you need things back regular type in the Immediate Window
application.EnableEvents=True
Try to open another workbook, and use statement application.enableEvents = false then before close this workbook, open workbook you wish

Excel Vba - Calling a sheet with a variable sheet name

I've been coding in VBA for some time, but this one has really stumped me.
I'm creating a workbook which creates technical certificates for machines. We have varying templates depending on the machine type and I am attempting to get my code to select the correct sheet from a user input and then populate the sheet. FYI these template sheets will be hidden and the user can only interact with the userforms.
Heres the code that is failing:
Machine = MachineType.Text '<-- input from userform, for example Machine = "Vertex 251"
Set wsCopy = ThisWorkbook.Sheets(Machine) '<--- select that machine's sheet
wsCopy.Copy '<--Run time Error 1004: Method copy of object_worksheet failed
I've tried numerous different types including just sheets(machine).copy or
Sheets(machine).activate
Activesheet.copy
but nothing has worked so far - I cannot tell if I am doing something fundamentally wrong.
Any help would be be appreciated.
Cheers.
You must unhide the sheet before copying it (at least to a new workbook as lturner notes) - you can then re-hide it
Dim shtTemplate as Worksheet, sheetWasHidden As Boolean
Set shtTemplate = ThisWorkbook.Sheets(Machine)
'handle the case where the sheet to be copied is Hidden
If shtTemplate.Visible = xlSheetHidden Then
shtTemplate.Visible = xlSheetVisible
sheetWasHidden = True
End If
shtTemplate.Copy
If sheetWasHidden Then shtTemplate.Visible = xlSheetHidden 're-hide if needed
When you have the worksheet object and use the Copy method, Excel seems to be making assumptions (or not) about where you want to put the new sheet. I pretty much always use the After option to define where the new sheet should go.
Option Explicit
Sub test()
Dim wsCopy As Worksheet
Set wsCopy = ActiveSheet
wsCopy.Copy After:=wsCopy
End Sub

Deleting hyperlinks performance

I want to delete all hyperlinks on currently active sheet via VBA.
For that I am using ActiveSheet.Hyperlinks.Delete command, which works fine and does not take virtually any time...
All that until I have opened two workbooks containing hyperlinks at the same time. In that case, the very same command takes much more time (minutes) to finish. It does its job, removing hyperlinks from the activesheet only, but in longer time. It seems somehow the other worksheets with hyperlinks is slowing it down.
I can have multiple workbooks opened at the same time, but they must not have any hyperlinks for the macro to work fast.
Can someone help me to overcome this?
I actually am in a situation where I frequently need to have both hyperlinks workbooks opened at the same time and running the macro which deletes hyperlinks.
This may not be ideal, but I'd consider starting your code with a check to see if other workbooks are open in the instance and if they are save the activeworkbook, open an new instance of excel and reopen the workbook in the new instance. Then run your code again.
Something like this to open the new instance:
Sub BlahBlah
if morethan1 then
CWb = ActiveWorkbook.name
ActiveWorkbook.save
Dim objXL
Set objXL = CreateObject("Excel.Application")
objXL.Visible = True
application.displayalerts = false
objXL.Workbooks.Open = CWb
application.displayalerts = True
end if
End Sub
If you isolate the workbook you should return to your normal runtime