Unable to suppress clipboard warning message when closing a file - vba

I have a Macro that opens a workbook (wb1) and copies it into another workbook (wb2), then closes wb1. However I am always prompted the message below that there is a large amount of clipboard data which I don't want to be prompted. After doing some research I found putting the 'Application.CutCopyMode' set to false (which clears the clipboard) would resolve this issue but it hasn't.
Application.CutCopyMode = False
...
'copy the range from source book
wb1.Worksheets("Sheet1").Range("A1:V2").Copy
'paste the data on the target book
wb2.Worksheets("Sheet1").Range("A1:V2").PasteSpecial
wb.Close savechanges:=False
How can I close the file without this message?

If you want to suppress any messages, add the following before closing the file:
Application.DisplayAlerts = False
If you want to clear the clipboard content, you should add the Application.CutCopyMode = False after performing the Copy/Paste operations. Like this:
...
'copy the range from source book
wb1.Worksheets("Sheet1").Range("A1:V2").Copy
'paste the data on the target book
wb2.Worksheets("Sheet1").Range("A1:V2").PasteSpecial
Application.CutCopyMode = False
wb.Close savechanges:=False

What exactly is the special pasting you want to do? If you just want to copy the values across, then instead of copying & pasting, just assign the values directly:
wb2.Worksheets("Sheet1").Range("A1:V2").value = wb1.Worksheets("Sheet1").Range("A1:V2").value

Related

Excel -Run Time Error 1004 'Application Defined or Object Defined Error'

I have an Excel 2003 spreadsheet ("Tune.xls") with some VBA. It always fails with error:
Run Time Error 1004 'Application Defined or Object Defined Error'
When I click debug it brings me to the following line in the code :
DataImport.Range("J10").Value = FileName 'Copy path and filename to worksheet "Import Data"
and also please look into whole code as follows:
'Ensure that all global (public) flags are initialized properly; they might have been
'changed before the user requested a data import.
Sub_Error = False
Changed_Model_1 = False
Changed_Model_2 = False
Plot_Model_1 = False
Plot_Model_2 = False
Updated_Model_1 = False
Updated_Model_2 = False
'Disable screen updating to avoid flicker when graph data is modified. Puting the focus away
'from the graph to worksheet "Data Import" speeds up the execution by a factor of about 4. This trick
'is ad hoc and I cannot explain why it works, but it does...
Application.ScreenUpdating = False
DataImport.Select
'Open window to select data file. If no file is opened, then the variable FileName will be false.
FileName = Application.GetOpenFilename("Text Files (*.txt; *.dat),*.txt;*.dat, Excel Files (*.xls),*.xls", , "Open Process Data File")
If FileName = False Then Exit Sub 'exit if no file was opened or cancel button selected
******DataImport.Range("J10").Value = FileName 'Copy path and filename to worksheet "Import Data"******
'Open data file as a workbook and use shortcut name "DataSheet" for worksheet containing data.
Workbooks.Open FileName:=FileName, updateLinks:=0 'does not update linked cells
Set DataSheet = ActiveWorkbook.ActiveSheet
Set DataBook = ActiveWorkbook 'use shortcut for Data workbook
'The data workbook might contain cells referencing a DDE link. This makes it hard to manipulate
'the cells. Therefore, the entire worksheet is copied and only the values are pasted back. This
'will essentially remove all the DDE references.
DataSheet.Cells.Select 'This selects all cells
Selection.Copy
Selection.PasteSpecial Paste:=xlValues
Please can somebody help me to get this working again?
1004 is an error which can come because of various reasons. In general, it may be because:
some of the objects are not defined correctly;
the worksheet is locked;
Thus, to check the first option write these two lines before the error:
MsgBox Filename
MsgBox DataImport.Name
and see what you get. You should get something for Filename (not an error) and the DataImport.Name should be the name of the sheet.
Concerning the second option - check whether the cells in DataImport are not locked.

VBA Cells.select copy paste not bringing images over consistantly

I have some data and some images on a sheet.
I have some code that copies the data & images from this sheet in one workbook to a sheet in another workbook.
The problem: it seems to be hit or miss if it will bring over the images. Sometimes they copy, sometimes they don't WTF?
wb.Sheets(form).Activate
wb.Sheets(form).Cells.Select
Selection.Copy
objwbk.Activate
ws.Range("A1").Select
ActiveSheet.Paste
Set
Application.CopyObjectsWithCells = True
Before copying
BTW your code
wb.Sheets(form).Activate
wb.Sheets(form).Cells.Select
Selection.Copy
objwbk.Activate
ws.Range("A1").Select
ActiveSheet.Paste
will reduce to:
Application.CopyObjectsWithCells = True
wb.Sheets(form).Cells.Copy ws.Range("A1")
I found the answer. I am creating a new book and pasting to the new book but it's in compatibility modes solve below
'Remember the users setting which currently is 97-2003 file format
SaveFormat = Application.DefaultSaveFormat
'Set it to the 2007-2010 file format xlsm
Application.DefaultSaveFormat = 52
'MAKE NEW BOOK HERE
'Set DefaultSaveFormat back to the users setting
Application.DefaultSaveFormat = SaveFormat
late (ok.. very late ..) answer but i've got the same problem today.
I've try to open the source workbook in read-only mode and it works for for me ™.
So, when you set your objwbk (somethink like set objwbk = open("c:\path\wbk.xls",,true) ) put the third argument to true.

Excel Macro for Updating log

I am looking to create a macro where I take what I have in a master file that is constantly being updating on the last row and placing this into a separate log file.
I would only like to copy specific cells from the last row of the original and paste them into the log file, i've gotten close I believe but need help with the following areas:
Selection of the specific columns in the last row
How to not have the log file open or activated at any point for this to happen when the Macro is run.
I apologize if this question has been answered but I can't seem to curate all the information I am finding online to an applicable solution. Here is the macro I have thus far...
' copy2 Macro
'
Range("B5000").End(xlUp).Select
Selection.EntireRow.copy
Windows("Daily Referral Log.xlsx").Activate
Range("A65536").End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
End Sub
Looks like you're trying to open the log workbook and paste the last row from a data file into it.
I think this is what you're looking for.
Please let me know if you need something else.
How to not have the log file open or activated at any point for this to happen when the Macro is run.
Regarding this line, I think I am understanding you right.
You don't want to have to open it yourself manually; you want the code to do it.
If that's not what you mean, please let me know (you will have to lock the file for write access to modify it regardless).
Sub CopyLastRowToLog()
Dim ThisWb, wb As Workbook
Set ThisWb = ThisWorkbook
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.ScreenUpdating = False
On Error Resume Next
Set wb = Workbooks.Open("FileName and Path Goes Here") 'Edit This Line
On Error GoTo 0
'Basic Error Handling - Probably worth adding ReadOnly check but keeping code short
If wb Is Nothing Then
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox ("Error Opening File")
Exit Sub
End If
'Put the names of the sheets you're using below.
'The first 2 sheets should be the sheet you're copying from
'The second 2 sheets should be the sheet you're copying to
ThisWb.Sheets("Sheet1").Range("A" & Sheets("Sheet1").UsedRange.Rows.Count).EntireRow.Copy _
wb.Sheets("Sheet1").Range("A" & Sheets("Sheet1").UsedRange.Rows.Count + 1)
wb.Close (True)
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Edit:
To answer your first question, the file name looks weird:
Workbooks.Open("C:\Users\EYousefi\Desktop[Daily Referral Log.xlsx]Sheet1")
It should probably be:
Workbooks.Open("C:\Users\EYousefi\Desktop\Daily Referral Log.xlsx")
You don't need to specify the sheet there.
Secondly, to copy specific columns, you would want to change the copy line.
I added 2 new variables to make it easier to read:
'Get the last rows for the workbooks
Dim ThisWBLR, FinalWBLR
ThisWBLR = ThisWB.Sheets("Sheet5").UsedRange.Rows.Count
FinalWBLR = wb.Sheets("Sheet1").UsedRange.Rows.Count+1
ThisWb.Sheets("Sheet5").Range("B" & ThisWBLR & ":D" & ThisWBLR).Copy _
wb.Sheets("Sheet1").Range("B" & FinalWBLR)
You can also specify individual pieces of data one at a time if it is easier for you:
'Copy B to B
ThisWB.Sheets("Sheet5").Range("B" & ThisWBLR).Copy wb.Sheets("Sheet1").Range("B" & FinalWBLR)
'Copy C to C
ThisWB.Sheets("Sheet5").Range("C" & ThisWBLR).Copy wb.Sheets("Sheet1").Range("C" & FinalWBLR)

Deleting Sheet with VBA crashes Excel

I am trying to delete a worksheet when the user click's on an image (button) in Excel. However this makes excel crash and restart, forgetting any unsaved progress.
This is my sub:
Sub DeletePlan()
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Dim SheetNamesToCopy As String
SheetNamesToCopy = ActiveSheet.Name
' Check what addon sheets exists for the media, then add existing ones to string
If CheckSheet("periodeplan", True) = True Then
ThisWorkbook.SheetS(SheetNamesToCopy & " - periodeplan").Delete
End If
If CheckSheet("ukesplan", True) = True Then
ThisWorkbook.SheetS(SheetNamesToCopy & " - ukesplan").Delete
End If
If CheckSheet("Input", True) = True Then
ThisWorkbook.SheetS(SheetNamesToCopy & " - Input").Delete
End If
SheetS("Totalplan").Select
ThisWorkbook.SheetS(SheetNamesToCopy).Delete
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
End Sub
The application crashes most of the time. But not always... Any ideas what might be wrong?
(I have tested and confirmed that the delete function causes the crash, but its not always the same sheet).
Edit: This function is not deleting the last sheet in the workbook. There are 20 more sheets. Also i use Application.Calculation = xlCalculationAutomatic, because there are allot of formulas, and i do not want excel to calculate changes before all is connected sheets are deleted.
Any hint or answer is appreciated :)
The error occurs when the button that initiates the macro is located on one of the sheets that are to be deleted.
So the answer is: Do not create a button (or image linked to a macro) that deletes the sheet it is on.
If anybody can add to this answer with a reason for this error, please do so ;)
I just ran into this problem myself! I'm going to defer to more experienced designers on a way to refine this technique, but as a general concept, I do have a working solution:
If you allow the macro to run it's course and then delete the sheet, it doesn't crash. Something like this:
Sub Delete_This_Sheet()
Application.OnTime Now + TimeValue("00:00:02"), "Watergate"
Sheets("Sheet with a death sentence").Visible = False
End Sub
Sub Watergate() 'To make things go away
Application.DisplayAlerts = False
Sheets("Sheet with a death sentence").Delete
Application.DisplayAlerts = True
End Sub
Resurrecting this thread because I had the same issue and want to share the solution.
I had a very simple sub to delete worksheets:
Sub deletetraindoc()
Dim ws As Worksheet
Application.ScreenUpdating = False
For Each ws In ThisWorkbook.Sheets
'This if statement looks for any worksheet that contains the term "Form"
'Any worksheet that contains that string will be deleted
If InStr(ws.Name, "Form") > 0 Then
Application.DisplayAlerts = False 'Deactivates the standard deletion confirmation
ws.Activate
ws.Delete 'Deletes the worksheet
Application.DisplayAlerts = True 'Reactivates display alerts
End If
Next
Application.ScreenUpdating = True
End Sub
This inconsistently caused crashing until I added the line "ws.Activate" to activate each worksheet before deleting, which seems to have resolved the issue. I've run into this problem in many other situations performing actions on worksheets, but it usually would result in an object error instead of a complete crash.
I found that in Office 2013, you cannot place a button that overlaps a cell that that macro changes. Interesting enough, it doesn't occur if the change is numeric in nature, but if it is alphanumeric, it blows up excel when you attempt to delete that tab. Turns out, it blows it up when attempting to delete the tab manually (by mouse click) or by the macro attempting to do it. THUS, my lesson learned from this thread and applying it to my specific situation is to never place a development button over the cell it changes (in my case, it was simply a cell that gives the status of what that macro was doing). Excel 2013 does not like that situation while Excel 2010 simply didn't care.
I do believe you nare right and the only way around this is to ensure this macro is on the total plan sheet. Also you're doing a few unnecessary steps and the select a sheet should be to activate and select a cell.
Sub DeletePlan()
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Dim SheetNamesToCopy As String
SheetNamesToCopy = ActiveSheet.Name
'dont delete total plan
If sheetnames = "Totalplan" then exit sub
SheetS("Totalplan").Activate
Activesheet.Cells(1,1).select
'Turn off errors if sheet doesn't exist
On error resume next
ThisWorkbook.SheetS(SheetNamesToCopy & " - periodeplan").Delete
ThisWorkbook.SheetS(SheetNamesToCopy & " - ukesplan").Delete
ThisWorkbook.SheetS(SheetNamesToCopy & " - Input").Delete
ThisWorkbook.SheetS(SheetNamesToCopy).Delete
On error goto 0
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
End Sub
You can delete the active sheet from a button (or image) on the active sheet. You just have to work around it.
ActiveSheet.Move before:=Worksheets(1)
Worksheets(2).Activate
Worksheets(1).Delete
I had a similar, but not identical problem. I had a macro that deleted all the chart sheets with the following command, but although it operated correctly, Excel 2013 was doomed to fail as soon as I tried to save the file, and would "recover" by reverting to the previously saved situation, throwing away any subsequent work:
Oh, and it worked fine until I moved from, I think it was, Excel 2010 to 2013, changing to Windows 10 at the same time.
The command of doom was:
ThisWorkbook.Charts.Delete
Thanks to some inspiration from the answers above, I first inserted a save before the deletion action and then changed the delete as follows (it turned out the saves were not after all needed but I like to have them there, even if I comment them out):
Dim graphSheet As Chart
ActiveWorkbook.Save
For Each graphSheet in this Workbook.Charts
graphSheet.Delete
ActiveWorkbook.Save
Next graphSheet
I should also mention that there is a preceeding Application.DisplayAlerts = False before the for loop and of course the Application.DisplayAlerts = True after the Next... statement to cut out the unwanted
are you sure you want to do this type question?
Again, thanks to your contributors for the inspiration.
I wanted a button that would delete a sheet, as the workbook was protected and could 'export' results but couldn't delete unwanted results.
My simple workaround was to have the macro hide the sheet, but then to delete the last hidden sheet, so the files dont become huge with dozens of hidden sheets.
I created a range in a hidden sheet called "DeleteSheet", to store the name of the hidden sheet.
Sub Delete_Sheet()
ActiveWorkbook.Unprotect Password:="Patrick2017"
ActiveSheet.Unprotect Password:="Patrick2017"
On Error Resume Next
' (In event there is no hidden sheet or the sheet is already deleted, resume next)
'The below finds the name of the previously hidden sheet to delete, and stores it.
Dim DeleteSheet As String
DeleteSheet = Range("DeleteSheet")
'The below is to avoid the main sheet being deleted
If ActiveSheet.Name = "POAL Calculator" Then
Exit Sub
End If
' The below stores the current sheets name before hiding, for deleting next time the
' macro is run
Range("DeleteSheet") = ActiveSheet.Name
ActiveWindow.SelectedSheets.Visible = False
' The below deletes the sheet previously hidden
Application.DisplayAlerts = False
Sheets(DeleteSheet).Delete
ActiveWorkbook.Protect Password:="Patrick2017"
Application.DisplayAlerts = True
End Sub
How about moving the button code to a module?
I have had an issue with that in Excel 2016 whereby Option explicit didn't work if the code was in a module, but if the code is in a module, then you 'should' be able to delete the sheet where the button was.

Don't Save macro

I need to open and close a file using a macro, but I don't want to save it. I can get to wear excel prompts you to Save or Don't save, what is the VBA command for dont save. This is what I am using I just need it to not save and close excel all the way.
Sheets("Sheet1").Select
Range("A1").Select
Sheets("Sheet6").Select
Range("A1").Select
Workbooks.Open Filename:= _
"X:\File.xlsx"
Workbooks.Close
Place False in first argument after Close method to tell VBA to not save the Workbook changes. So:
Workbooks.Close False
or
Workbooks.Close SaveChanges:=False
If I understand well, try to use Application.DisplayAlerts:
Application.DisplayAlerts=False
Workbooks.Close
Application.DisplayAlerts=True
You can use the Saved property of the Workbook object for this. Setting this property to True will stop the prompt from appearing (but won't actually save the workbook):
Dim wb as workbook
Set wb = Workbooks.Open("X:\File.xlsx")
' do stuff here
wb.Saved = True
wb.Close
See http://msdn.microsoft.com/en-us/library/ff196613.aspx for reference