Run-time error '-2147188160(80048240) DataType:=ppPasteEnhancedMetafile Error - vba

Seems there is some bug. Can't resolve this problem, all code is running fine and I am able to see the AutoShape is getting copied from Excel file but it is not adding it to PowerPoint. Popping up an error Run-time error '-2147188160(80048240) View.Pastespecial : Invalid Request. The specified data type is unavailable
If Range("H" & i).Value = 1 And Range("B" & i).Value = "FRONT" Then
objPPT.Presentations(1).Slides(9).Select
objPPT.ActiveWindow.View.PasteSpecial DataType:=ppPasteEnhancedMetafile

Your code will be faster and possibly more reliable if you don't rely on selecting anything:
With objPPT.Slides(9).Shapes
Set objShape = .PasteSpecial(ppPasteEnhancedMetafile)(1)
With objShape
' set coordinates and such here
End With
End With
As to why you're getting the error message, try stopping the code after you've put something on the clipbard. Then switch to PowerPoint, use Paste Special to see what paste options are available. If EMF isn't one of them, that's your problem ... you're not putting anything in EMF format on the clipboard.

I had a similar issue, but I found a different solution; it may be specific to what I was doing though.
I setup a program where I would:
(manual) Copy an entire webpage that was a report on several performance metrics
(manual) Pasted it in to excel
Run the program to extract the values I want and then clear contents of the sheet I pasted them on.
Eventually after many tests, it would fail with this same automation error when I tried to access the sheet:
Sheets("PDX Paste").Activate
I was able to activate every other sheet except that particular one, even using the index value instead of the direct name reference. After googling to no success I found out that the copy and paste from the website was also pasting invisible controls. When I found this out I had 1,300+ shapes when I only expected 1 (the button I use to trigger the program). It was actually only apparent when a glitch - presumably due to so much memory being used to store these controls - displayed for a few seconds.
I ran the following code independently and then appended it to the end of my program when I do the cleanup of the data. The code goes through the sheet and deletes any shape that isn't the same type as my button. It would have to be adapted if the shapes you want to delete are the same type as the shapes you want to keep. It also becomes simpler if you don't have any shapes to keep.
Dim wsh As Worksheet
Set wsh = ActiveSheet
Dim i As Integer
For i = wsh.Shapes.Count To 1 Step -1
If wsh.Shapes(i).Type <> wsh.Shapes("UpdateDataButton").Type Then
wsh.Shapes(i).Delete
End If
Next i
I'm not sure this would solve this problem, but hopefully this can help others and prevent loss of time figuring out what may be causing this relatively vague error message.

Related

Error 91 when using Cells.Find with window hidden

Please read this fully and understand that this program was working fine until I changed the way I was hiding the workbook.
I have a program that worked great while I was using Application.Visible = False and only showing the user form. I came to realize that this would hide all Excel windows and not just the one I was using. This is going to be distributed throughout the department and hiding all Excel windows was unacceptable.
I started using ActiveWindow.Visible = False, but I am now getting Error 91 anytime I search a worksheet for a value (Cells.Find).
Modifying the worksheet is not an option and the value for which I'm searching can move around the sheet depending on what has been added or removed.
Cells.Find worked out great for this reason. I need to either find another way to search the page, or find another way to hide the worksheet. Please help
When the window is not visible, the Cells reference is not qualified to a worksheet object (unless qualified, Cells refers to ActiveSheet.Cells and there is no ActiveSheet), so you can do like:
Sheets("sheetname").Cells.Find ' modifying "sheetname" as needed
This may also fail (with the same error), or it could also yield incorrect results if there are other open workbooks, so it's best to qualify to a workbook fully, e.g.:
Workbooks("workbookname").Sheets("sheetname").Cells.Find(...
It is still a good idea to test the result of Find before performing additional method/property calls against an object which could be Nothing, as per this answer:
Find command giving error: "Run-time Error '91': Object variable or With block variable not set"

Search/Copy/Insert VBA Macro causing multiple different crashes in Excel 2016

I'm experiencing a strange issue occurring with my VBA Macros in Excel. Background is, I'm creating a template for Labour Logs to log hours that employees are on site. There is a main sheet where all the data is entered "Labour Log" and then 8 sheets, one for each of the days of the week and a Holidays sheet. There is a hidden sheet where my dynamic list and static lists are held.
The macros that are causing issues are the ones on the sheets for the days of the week. What they are doing is, searching the Labour Logs sheet for any cell with that day of the week in column B, then inserting that line on row 8 of the day sheet. This loops until all instances are entered. Example of Monday below.
Private Sub PullMondayData_Click()
Dim dc As Range
With Sheets("Labour Log") 'Reference to Labour Log Sheet
For Each dc In Intersect(.Range("B:B"), .UsedRange)
If dc.Value2 = "Monday" Then 'Search/Filter B:B for Monday
dc.Resize(1, 1).EntireRow.Copy 'Copy the row
Sheets("Monday").Rows(8).Insert Shift:=xlDown 'Insert in Row 8, shifting down
End If
Next
End With
Application.CutCopyMode = False 'Remove copy mode
End Sub
This usually works fine for Monday. I can usually hit that one multiple times without issue.
When I go back to the Labour Log sheet and change the day to any other day, I start getting errors on those sheets when hitting the macro. The macro codes is exactly the same, but with the relevant day entered in the correct spots.
The first error I usually get is:
Going to debug says error with this line:
I then stop the macro and run it again, getting the following error:
Debugging it gives this line:
After that, the only way I can close the Excel sheet is to end the process form the Task Manager, the rest of the program is locked.
From time to time, I also get a crash, and the output is this:
Problem signature:
Problem Event Name: APPCRASH
Application Name: EXCEL.EXE
Application Version: 16.0.6868.2060
Application Timestamp: 5723a711
Fault Module Name: mso20win32client.dll
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 57222bc3
Exception Code: c0000005
Exception Offset: 0008c78d
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 4105
Additional information about the problem:
LCID: 1033
skulcid: 1033
I've searched online for various answers, but they don't seem to work. I've tried the following:
Clearing the Excel folder in C:\Users\User_Name\AppData\Roaming\Microsoft\Excel
Cleaning the Registry
Changning the set printer (long shot, but saw a few people say it worked)
Running another day before Monday
Running Windows Update
Moving Application.CutCopyMode = False within the If loop
My knowledge of VBA isn't great and a lot of this code was taken from searches and altered to suit my purpose, but I don't understand why it is working for the Monday sheet, but crashes on all others.
Any insight would be much appreciated.
Thanks.
too little info to actually track that error down
but, assuming you're using a Userform with many buttons to click and have proper day processed, I'd propose you some code that can possibly help you keep things cleaner and, therefore, less prone to errors
set your buttons caption property as per the relevant day
so you'll have
PullMondayData button showing "Monday" caption on it
PullTuesdayData button showing "Tuesday" caption on it
and so on
have all your Pulldaybutton "Click" event handlers code just like follows:
Private Sub PullMondayData_Click()
PullDayData (Me.ActiveControl.Caption)
End Sub
Private Sub PullTuesdayData_Click()
PullDayData (Me.ActiveControl.Caption)
End Sub
and so on
add the following sub to your Userform code pane
Private Sub PullDayData(thisDay As String)
Dim dc As Range
With Sheets("Labour Log") 'Reference to Labour Log Sheet
For Each dc In Intersect(.Range("B:B"), .UsedRange)
If dc.Value2 = thisDay Then 'Search/Filter B:B for Monday
With Sheets(thisDay).Rows(8)
.Insert Shift:=xlDown 'Insert in Row 8, shifting down
.Value = dc.Resize(1, 1).EntireRow.Value
End With
End If
Next
End With
End Sub
all what above can still greatly improved, but it'll give you at least the following benefits:
write much less code
and thus both make much less effort in maintaining it and possibly have many few errors!
not make use of copy/paste methods to both not passing through clipboard and be faster
For further effective improvements I'd suggest you the following steps:
use AutoFilter() and SpecialCells() methods of Range object to improve both control and efficency
use classes
While I agree with user3598756 that this isn't enough to give an answer with certainty, I do have some additional things to try:
I've had much better results using .CurrentRegion, than .UsedRange to get the area of data. There are exceptions, but if you have headers that can't be blank and at least one column with no blanks, it works flawlessly.
When you have more than one thing on a line causing an error, breaking it out will give you better info about crashes, so change: dc.Resize(1, 1).EntireRow.Copy into two statements: dc.Resize(1,1) and dc.EntireRow.Copy.
COM objects, and Range objects like .Rows(x) in particular, are tricky beasts. This seems to be worse in C# addons than VBA macros, but I've often seen them not update as expected when you do something to major their contents. The work around is the general case of the specific case I gave in point 2: one dot good, two dots bad. For example instead of calling Sheets("Monday").Rows(8).Insert try something like:
Dim MondaySheetRow as Range
MondaySheetRow = Sheets("Monday").Rows(8)
MondaySheetRow.Insert Shift:=xlDown
Lastly I've made a habit of not updating sheets that aren't active. Instead I activate the sheet I'm going to make changes to, make the changes, then return to the originally active sheet. This mimics the way a user would manually make the changes which also helps visually show where the macro went in the calls leading up to an error.

How do I delete VBA code from a sheet using VBA?

I want to delete the VBA code contained within a sheet through VBA. Currently, I have a code that copies a sheet across to a new workbook and deletes all images from it. However, these images are set to do things on Worksheet_Activate in the code, which then causes an error whenever I flick to that sheet with no images there.
I know I can get rid of modules etc using something along the lines of:
With ActiveWorkbook.VBProject
For x = .VBComponents.Count To 1 Step -1
.VBComponents.Remove .VBComponents(x)
Next x
For x = .VBComponents.Count To 1 Step -1
.VBComponents(x).CodeModule.DeleteLines _
1, .VBComponents(x).CodeModule.CountOfLines
Next x
End With
but that does not delete from the sheet (or the workbook for that matter. Would be interesting to know if that was possible too).
The code itself will need to be valid for Excel versions 2003 through to 2013 (so cannot use the save as xlsx workaround).
Found out the issue. My code works fine, just the computer I was testing it on did not allow access to the VBA project object model (and was running it with an On Error Resume Next earlier on in the code)
Will have to write an exception in to sort that out in such cases.
Thanks to #mehow #nixda #SiddharthRout and #DaveU for the help

Method Select of Object '_Worksheet' failed - why?

Set mainWB = Workbooks("Copy Paste.xlsb")
Set mainWS = mainWB.Sheets("Sheet1")
Set testWS = mainWB.Sheets("Sheet3")
mainWS.Select
I keep getting an error on the last line in Excel VBA:
"Method Select of Object '_Worksheet' failed"
Any idea why or how to fix this? Thank you!
As discussed in comments, cannot select Sheets in VBA that are not active (or Range objects on them).
For example the following code
Sheets(1).Activate
Sheets(2).Range("A1").Select
will cause the error you are receiving.
In your case, it seems you are attempting to Select a sheet which is not active - your mainWS object is presumably not the ActiveSheet at the point you are calling this code. An easy way to test if this is happening is if you add the following to the end of your code:
if (ActiveSheet.Name <> mainWS.Name) then
msgbox ("Going to crash after clicking ok!")
end if
mainWS.Select
Note that you can refer to the activated worksheet with the command ActiveSheet to either get properties or whatever other operations you are interested in doing.
This error can also happen if you have loop working thru all of the worksheets in the workbook and there are hidden sheets. Lookout for that.
Last, and unrelated to your specific error message, I assume you are declaring those variables somewhere and simply did not copy them here - if not I would consider using Option Explicit as you can often run into all sorts of issues without having Option Explicit at the top of your VBA code.
While I agree with the above, it is also important to note that the Delete function will not work if the worksheet's visibility is currently set to xlSheetVeryHidden
I had the same issue and looked at this post for ideas on how to fix it. My issue was resolved by using "Activate" as opposed to "Select" on the line that my code was failing on. So instead of using "mainWS.Select", try using "mainWS.Activate" instead.

What could cause Shape.Cut to fail in Excel VBA?

I have a method in my macro that executes the following code:
Set myDocument = Worksheets("sheet1")
For each sh in myDocument.Shapes
If sh.Name = "square" Then
sh.Cut
End If
Next
My problem is that the code causes an error on the line sh.Cut. I know that there is a shape called "square" - I can see (visually) the shape in the document, but Excel just doesn't want to cut that shape out. Any suggestions as to why this might be?
EDIT: To clarify, this behaviour does not always happen. Usually it is alright - it only seems to happen sometimes, but I can't see any co-relation between the times that it happens.
Thanks.
There's only two reasons to ever use the Select method. 1) You want to select something. 2) You're working with shapes and getting weird errors. It doesn't make sense, but try
sh.Select
sh.Cut
and I'll bet it will work every time.