Copy ppt into Excel with formatting - vba

I am trying to copy from powerpoint to excel and trying to keep the power point formating.
For x = 1 To pptApp.ActivePresentation.Slides.Count
pptApp.ActivePresentation.Slides.Range(Array(x)).Select
pptApp.ActivePresentation.Slides.Range(Array(x)).Copy
pptApp.Windows(2).Activate
pptApp.ActiveWindow.View.Paste
pptApp.Windows(2).Activate
Next x
I'm currently using this to do the copy and it works fine, however it doesn't copy the formatting.
Any Ideas how to achieve this?
Sp

On top of PaulStock's valid point, when you paste from one office application to another the buffer can be interpreted in many different ways by the importing program. In your case you want to make sure that Excel imports the PPT slide not as HTML, text, BMP or any other, but as a slide object. In the interactive mode you would use the PasteSpecial command, and a VBA aequivalent in Excel would be
[SheetObject].PasteSpecial Format:="Microsoft PowerPoint Slide Object", _
Link :=False, _
DisplayAsIcon:=False
quick & dirty testing: put this code in a sheet-onDoubleClick trigger, replacing [SheetObject] by "Me", move to PPT, copy a slide from the slide strip (!!!), go back to Excel and doubleclick a cell - and voi lá!
(here Office 2003 SP3)

Related

Excel VBA add hyperlink to shape to link to another sheet

I have a macro that creates a summary sheet at the front of a Workbook. Shapes are created and labeled after the sheets in the workbook and then hyperlinks are added to the shapes to redirect to those sheets, however, when I recorded the macro to do this, the code generated was:
ActiveSheet.Shapes.Range(Array("Rounded Rectangle 1")).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection.ShapeRange.Item(1), Address:=""
The hyperlinks that were manually created in excel while recording the macro work just fine and when hovering over them, display the file path and " - Sheet!A1" but they don't seem to actually be adding the link location into the address portion of the macro. Does anyone know the code that should go in that address section to link to the sheet?
The macro recorder doesn't record what is actually happening in this case. The property you are looking for is SubAddress. Address is correctly set in your code.
Create a hyperlink from a shape without selecting it
You want to avoid selecting things in your code if possible, and in this case it definitely is. Create a shape variable and set it to the shape you want to modify, then add the hyperlink to the sheet the shape is on. Note that you can also set the text for the screen tip.
In the example below, the shape I want to modify is on Sheet 6, and hyperlinks to a range on Sheet 4.
Sub SetHyperlinkOnShape()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet6")
Dim hyperLinkedShape As Shape
Set hyperLinkedShape = ws.Shapes("Rectangle 1")
ws.Hyperlinks.Add Anchor:=hyperLinkedShape, Address:="", _
SubAddress:="Sheet4!C4:C8", ScreenTip:="yadda yadda"
End Sub

copy selection from chrome to excel

I'd like to create a quick way of copying and pasting in between Chrome and Excel. The program would need to perform a task of pasting the selection in a given cell. If we access Excel it's fairly easy, we just need to use Microsoft Forms Library in order to get what we copied to clipboard and paste it in the highlighted field. I'd like to extend this process. Now it looks as follows:
I copy something in Chrome
I need to switch to Excel and access the macro in order to paste what's selected
What I have so far:
Option Explicit
Public Clipboard As New MSForms.DataObject
Sub pasteTable1()
'Tools -> References -> Microsoft Forms 2.0 Object Library
'of you will get a "Compile error: user-defined type not defined"
Dim DataObj As New MSForms.DataObject
Dim S As String
DataObj.GetFromClipboard
S = DataObj.GetText
Debug.Print S 'print code in the Intermediate box in the Macro editor
ActiveSheet.Paste Destination:=Worksheets("Arkusz1").Range("A1")
End Sub
Would it be possible to skip the intermediate step and make Excel paste what's in the clipboard without having to open it? In other words I'd like to have a way of pasting the contents of clipboard automatically once the selection is made.

Excel VBA runtime error 1004

I'm trying to write a macro to paste special formulas but keep getting a runtime error 1004 "PasteSpecial method of Range class failed".
This macro comes directly from using the "Record Macro" provided by Excel.
Sub paste_formulas()
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End Sub
Here is the sequence of events:
Manually select a range of cells in CSV file A and copy (CTRL+C).
Switch to the XLS file B and select the cell were I want the copied data pasted.
Press Macros and run personal.xlsm!paste_formulas
That's when I get the error. Why does this work manually when I copy/paste-special formulas, but fail in the macro?
Note: I need this to work in the above sequence regardless of the selected range that I copy (will vary from time to time), and regardless of the location I paste formulas to (will also vary from time to time). In other words, hardcoding a fixed range for copy and/or paste won't work for me.
Thanks in advance for any help understanding why my code isn't working or providing a work-around.
The reason is very simple, When you copy from the CSV and then in your workbook, click on Macros in the Developer Toolbar, Excel clears the clipboard.
Excel has this habit of clearing the clipboard when you click on Developer | Macros. To demonstrate this, copy the cells from the same workbook. You will see the ant like border around the cells. Now in the same workbook, click on Developer | Macros. The Ant like borders will disappear :)
Set a shortcut key for your macro and use that. it will work :)

Using vba to copy the contents of a word document into another word document

I haven't used VB for years, so please forgive me if this turns out to be obvious. I'm trying to write a word vba macro for use in a template which will display a userform and then import the contents of fileA.docx, fileB.docx, or fileC.docx depending on the userform. (After that I'm going to use bookmarks to fill in some form data, I don't know if that's relevant). Files A, B, and C will contain text with some basic formatting such as lists, but nothing fancy.
The solutions I've seen online can copy the contents of file to a new file, but ideally I would like to import the entirety of one of those files into the new, currently unnamed file that I'm getting from the template. I think where I'm running into problems is with switching the selection to one of those files, and then back to the new unnamed document, though I could use a hand to make sure I'm copying correctly as well.
Update: I was making things too hard, though the answers here got me pointed in the right direction (thanks!). In the end I just did
ThisDocument.Activate
Selection.InsertFile("fileA")
which gives me the raw dump of everything that I wanted.
Using commands such as these you can switch between which Document you're using and copy and paste elements:
ThisDocument.Activate 'Sets the main document active
Documents("Name.doc").Activate 'Activates another document
You can insert, copy and paste things in and out of documents using copy commands.
ThisDocument.Range.InsertAfter("String") 'Insert text
Selection.WholeStory 'Select whole document
Selection.Expand wdParagraph 'Expands your selection to current paragraph
Selection.Copy 'Copy your selection
Documents("name.doc").Activate 'Activate the other document
Selection.EndKey wdStory 'Move to end of document
Selection.PasteAndFormat wdPasteDefault 'Pastes in the content
You can then go and format such, or copy and paste them with original formatting from before.
Here is a significant improvement (I think) you will want to incorporate because it:
does not use the clipboard and thus does not make your macro vulnerable to the user changing the contents of the clipboard while your macro is running
does not use a file and thus greatly improve the speed by eliminating I/O and eliminates the potential of having to deal with file system security/permissions, etc. Please do not use .InsertFile() if you are looping through documents you will slow yourself down. Use it once, at the end -only if you have to. The example below shows how to accomplish the same result without using .InsertFile()
The idea is to transfer some portion of text found in 1 source document, to a destination document that is different than the source, and keep the source formatting.
To accomplish the above (skipping the code to open documents):
For Each oTable In oDoc_Source
'the above could have been anything that returns a Range object
'such as: ActiveDocument.Content.Find.Execute ....
'...
'logic here to identify the table, or text, you are looking for
'...
'I can't believe the MS Dev Center folks could only think
'of .InsertFile(), which is the last resort I would go for,
'especially if your code runs on a web server [concurrent web requests]!
'SAFEST
'(no user interference on clipboard possible, no need to deal with file i/o and permissions)
'you need a reference to Document.Content,
'as the act of obtaining a reference "un-collapses" the range, so the below 3 lines must be in that order.
Set oRange = oDoc_DestinationDoc.Content
oRange.Collapse Direction:=wdCollapseEnd
oRange.FormattedText = oTable.Range
'BRUTE, AND PRONE TO RANDOM ERRORS AND HANGS DUE TO USER INTERFERENCE WITH CLIPBOARD
'find a way to implement WIHTOUT using the CLIPBOARD altogether to copy the below range object
'it will be easier for PC users to use the clipboard while the macro runs
'and it will probably be safer for the output of this macro to remain uncorrupted
'oTable.Range.Copy
'Set oRange = oDoc_DestinationDoc.Content
'oRange.Collapse Direction:=wdCollapseEnd
'oRange.Paste
'THE BELOW DOES NOT WORK
' '1) - cannot add a range from another document
' 'adds only text, not the formats and not the table layout
' oTable.Range.TextRetrievalMode.IncludeFieldCodes = True
' oTable.Range.TextRetrievalMode.IncludeHiddenText = True
' oDoc_DestinationDoc.Content.InsertAfter oTable.Range
'
' '2) - cannot add a range from another document
' oDoc_DestinationDoc.Content.Tables.Add oTable.Range, iRowMax, iColMax
'
' '3) - only puts in plain text, and it replaces the range without the .Collapse call
' oDoc_DestinationDoc.Content.Text = oTable.Range
Record a macro...
start in the source document
press ctrl-a to select everything
press ctrl-c to copy it to the clipboard
switch to the target document
press ctrl-v to paste into the document
stop recording
or (assuming word 2007 or later)
start in the target document with the source document closed
on the ribbon click insert > object > Text from file...
navigate to the source document
click the insert button
stop recording
I prefer the second version so I should have put it first
I was doing the same thing, tried to select the other document, copy and paste. But it didn't worked (I received an error probably because some other application was using the clipboard, but I am not sure.). So I did a little search and found the perfect solution on Microsoft Dev Center.
https://msdn.microsoft.com/en-us/vba/word-vba/articles/selection-insertfile-method-word
Selection.Collapse Direction:=wdCollapseEnd
Selection.InsertFile FileName:="C:\TEST.DOC"
'set current doc name and path
Dim docName As String: docName = ActiveDocument.name
Dim filepath As String: filepath = ActiveDocument.Path
'create a new file
Documents.Add
'get the path of a current file
ChangeFileOpenDirectory filepath
'insert content of current file to newly created doc
Selection.InsertFile _
FileName:=docName, _
Range:="", _
ConfirmConversions:=False, _
Link:=False, _
Attachment:=False
'open prompt to save a new file
With Dialogs(wdDialogFileSaveAs)
.name = docName & "-copy"
.Show
End With

How to edit / ungroup EMF pastes in PPT using VBA?

it's Martin from Berlin (Germany - so please excuse my wrong English)...
I'm trying to edit EMF pastes in PPT using VBA. The EMF pastes are Excel charts and I used
ActiveWindow.Selection.SlideRange.Shapes.PasteSpecial DataType:=3 (enhanced metafile)
Without VBA it is easy: Just rightclick the image and "ungroup" (2x).
In VBA I tried the following:
1. Selecting the right shape (works), then
ActiveWindow.Selection.ShapeRange.Ungroup.Select
This runs on an error: "...cannot ungroup".
In another thread a "solution" was given: Recording a macro -> not possible in PPT 2007!
When I record a macro in PPT 2003, it says exactly the same:
ActiveWindow.Selection.ShapeRange.Ungroup.Select
but it doesn't work.
It seems that there should be one step before that converts the emf image into "office format" (if you do it without VBA after clicking "ungroup" a message box occurs that askes, if you want to convert the graphics into "office format").
Any idea what to do that ungroup is working with VBA?
This works here:
Sub UngroupPastedChart()
Dim oShRange As ShapeRange
Dim oSh As Shape
Set oShRange = ActiveWindow.Selection.SlideRange.Shapes.PasteSpecial(ppPasteEnhancedMetafile)
Set oShRange = oShRange.Ungroup
Set oShRange = oShRange.Ungroup
End Sub
and add oShRange.Select if you want the ungrouped shapes to be selected at the end.