Strange behavior on running Powerpoint VBA updating Excel links - excel

I need some help with some bizzare VBA code behavior in Powerpoint. Purpose is simple - update Excel links on a Powerpoint presentation. I have a presentation with objects linked to an Excel file. On running the code from Powerpoint, a user is prompted to select the source Excel file on the harddrive, and the location of this Excel file is used to replace the previous location of the Excel file, already saved in the PowerPoint presentation.
You run the macro, check the links, their path is updated. You click save, close the presentation. You open the presentation and all is good.
Now let’s say you change the name of the Excel file. You run the macro, check the links, their path is updated. You click save, close the presentation. You open the presentation and ONLY HALF THE LINKS ARE UPDATED. Could somebody take a look? Thanks!
Private Sub CommandButton1_Click()
Dim xlApp As Object
Dim xlWorkBook As Object
Dim pptSlide As Slide
Dim pptShape As Shape
Dim oldString, tempString, newString As String
Dim intLength As Integer
Dim sPath As String
Dim ExcelFileName As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file to update links in the presentation"
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel Workbook", "*.xlsx"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
newString = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
'show "macro running" screen
UserForm1.Show False
'open excel file with links
Set xlApp = CreateObject("Excel.Application")
Set xlWorkBook = xlApp.Workbooks.Open(newString, True, False)
'grab old full path to replace link in objects
For Each pptSlide In ActivePresentation.Slides
For Each pptShape In pptSlide.Shapes
If pptShape.Type = msoLinkedOLEObject Then
tempString = pptShape.LinkFormat.SourceFullName
intLength = InStr(tempString, "!")
oldString = Mid(tempString, 1, intLength - 1)
GoTo 1
End If
If pptShape.Type = msoChart Then
oldString = pptShape.LinkFormat.SourceFullName
GoTo 1
End If
Next pptShape
Next pptSlide
1
'replace old full path to new full path
For Each pptSlide In ActivePresentation.Slides
For Each pptShape In pptSlide.Shapes
If pptShape.Type = msoLinkedOLEObject Or pptShape.Type = msoChart Then
With pptShape.LinkFormat
If InStr(1, UCase(.SourceFullName), UCase(oldString)) Then
.SourceFullName = Replace(.SourceFullName, oldString, newString)
End If
End With
pptShape.LinkFormat.Update
End If
'DoEvents
Next pptShape
'DoEvents
Next pptSlide
'close excel file with links
xlWorkBook.Close (False)
xlApp.Quit
Set xlApp = Nothing
Set xlWorkBook = Nothing
'hide "macro running" screen
UserForm1.Hide
End Sub

Related

Opening and Saving Word Document to new File Location from Excel

I am trying to open a word document from excel and then save as to a new file location using a dialog box.
The problem is it saves the excel file rather than the word file that was opened.
Option Explicit
Sub SaveWordDoc()
Dim WordApp As Object, WordDoc As Object, path As String
Dim dlgSaveAs As FileDialog
' Allows word document to be selected and opened
With Application.FileDialog(msoFileDialogOpen)
.Show
If .SelectedItems.Count = 1 Then
path = .SelectedItems(1)
End If
End With
If path = "" Then
Exit Sub
End If
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(path)
WordApp.Visible = False
'Opens Save As dialog box
Set dlgSaveAs = Application.FileDialog( _
FileDialogType:=msoFileDialogSaveAs)
dlgSaveAs.Show
WordApp.ActiveDocument.Close
WordApp.Quit
Set WordApp = Nothing
Set WordDoc = Nothing
End Sub
Thank you BigBen your suggestion works well as long as the a word document format is selected.
Option Explicit
Sub Test()
Dim WordApp As Object, WordDoc As Object, path As String
Dim dlgSaveAs As FileDialog, fileSaveName As Variant
' To get the code to function I had to include the Microsoft Word 16 Object
'Library.
'From the excel VBA editor window. Tools > References then ensure Microsoft Word
'16.0 Object Library is checked.
' Allows word document to be selected and opened
With Application.FileDialog(msoFileDialogOpen)
.Show
If .SelectedItems.Count = 1 Then
path = .SelectedItems(1)
End If
End With
If path = "" Then
Exit Sub
End If
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(path)
WordApp.Visible = False
' Allows word document to be saved under a different file location and name
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Word Documents (*.docx), *.docx")
WordApp.ActiveDocument.SaveAs2 Filename:=fileSaveName, _
FileFormat:=wdFormatDocumentDefault
WordApp.ActiveDocument.Close
WordApp.Quit
Set WordApp = Nothing
Set WordDoc = Nothing
End Sub

Want a VBA code in powerpoint to show all charts in excel to different slides in ppt

I have developed vba code in excel to show all charts in excel to different slides in ppt. But i want the vba code to be implemented in powerpoint instead of excel so that i can create an addin in powerpoint with that macro. I have tried to implement the excel vba code in powerpoint but that doesnot work in ppt. The problem is that it is copying the charts from the excel to the ppt slides.`I have used the following code in ppt but with no success.
Sub Button1()
Set pptApp = New PowerPoint.Application
Set pptPres = pptApp.ActivePresentation
Dim xlApp As Object
Dim xlWorkBook As Object
Dim wb As Workbook
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open("C:\Users\tonmoy.roy\Desktop\Meeting Files\Monthly Review July 10.xls", True, False)
Dim WAIT As Double
WAIT = Timer
While Timer < WAIT + 10
DoEvents 'do nothing
Wend
wb.Activate
Dim ws As Worksheet
Dim intChNum As Integer
Dim objCh As Object
'Count the embedded charts.
For Each ws In wb.Worksheets
intChNum = intChNum + ws.ChartObjects.Count
Next ws
'Check if there are chart (embedded or not) in the active workbook.
If intChNum + ActiveWorkbook.Charts.Count < 1 Then
MsgBox "Sorry, there are no charts to export!", vbCritical, "Ops"
Exit Sub
End If
'Loop through all the embedded charts in all worksheets.
For Each ws In wb.Worksheets
For Each objCh In ws.ChartObjects
Call pptFormat(objCh.Chart)
Next objCh
Next ws
'Loop through all the chart sheets.
For Each objCh In wb.Charts
Call pptFormat(objCh)
Next objCh
'Show the power point.
pptApp.Visible = True
'Cleanup the objects.
Set pptSlide = Nothing
Set pptPres = Nothing
Set pptApp = Nothing
'Infrom the user that the macro finished.
MsgBox "The charts were copied successfully to the new presentation!", vbInformation, "Done"
End Sub
Private Sub pptFormat(xlCh As Chart)
'Formats the charts/pictures and the chart titles/textboxes.
Dim chTitle As String
Dim j As Integer
On Error Resume Next
'Get the chart title and copy the chart area.
chTitle = xlCh.ChartTitle.Text
xlCh.ChartArea.Copy
'Count the slides and add a new one after the last slide.
pptSlideCount = pptPres.Slides.Count
Set pptSlide = pptPres.Slides.Add(pptSlideCount + 1, ppLayoutBlank)
'Paste the chart and create a new textbox.
pptSlide.Shapes.PasteSpecial ppPasteJPG
If chTitle <> "" Then
pptSlide.Shapes.AddTextbox msoTextOrientationHorizontal, 12.5, 20, 694.75, 55.25
End If
'Format the picture and the textbox.
For j = 0 To pptSlide.Shapes.Count
With pptSlide.Shapes(j)
'Picture position.
If .Type = msoPicture Then
.Top = 87.84976
.Left = 33.98417
.Height = 422.7964
.Width = 646.5262
End If
'Text box position and formamt.
If .Type = msoTextBox Then
With .TextFrame.TextRange
.ParagraphFormat.Alignment = ppAlignCenter
.Text = chTitle
.Font.Name = "Tahoma (Headings)"
.Font.Size = 28
.Font.Bold = msoTrue
End With
End If
End With
Next j
End Sub
Private Sub pptFormat(xlCh As Chart) should be :
Private Sub pptFormat(xlCh As Excel.Chart).
PowerPoint has a Chart in its Object Model, so you need to change it to explicitly say Excel.Chart
I am assuming you already have the references
If intChNum + ActiveWorkbook.Charts.Count < 1 Then should be:
If intChNum + wb.Charts.Count < 1 Then
Also your variables aren't declared properly as far as I can see in the pptFormat function. Dim them and use Option Explicit in your coding.
Option Explicit helps in long run more than any inconvenience of having to type out decs.
Tonmoy Roy,
You should ask your second question in another thread. But here is some code to have you select a file and get it's name, path or just the entire name/path
Set XLapp = New Excel.Application
'choose the data file
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Select the Data File (Data File.xlsx)."
'clear filters so all file are shown
.Filters.Clear
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
FullName = .SelectedItems(1) 'name and path
End If
End With
fname = Dir(FullName) ' gets just the file name and not the path
XLapp.Visible = True
Set xlWorkBook = XLapp.Workbooks.Open(FullName, False, True) 'Opens the data xlsx file

Copying & Pasting information from Microsoft Word OLEObject to Excel file via VBA

My issue is after I have imported a table from Microsoft Word into Excel by creating an OLEObject, it won't let me copy and paste the table into excel. It continually keeps pasting whatever was last copied on my clipboard into the first cell. Currently my code asks the user for the file name, opens that file as an OLEObject in the active excel sheet, and then pastes the incorrect information into cell A1. It's not copying and pasting what's inside the Word OLEObject.
Sub Macro1()
Dim FName As String, FD As FileDialog
Dim ExR As Range
Set FD = Application.FileDialog(msoFileDialogOpen)
FD.Show
If FD.SelectedItems.Count <> 0 Then
FName = FD.SelectedItems(1)
Else
Exit Sub
End If
ActiveSheet.OLEObjects.Add(fileName:=FName, Link:=False, DisplayAsIcon:=False).Select
Selection.Verb Verb:=xlPrimary
Range("A1").Select
ActiveSheet.Paste
End Sub
Thank you!
From Word to Excel, should be something like this.
Sub ImportFromWord()
'Activate Word Object Library
'Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Set WordApp = CreateObject("word.application") ' Open Word session
WordApp.Visible = False 'keep word invisible
Set WordDoc = WordApp.Documents.Open("C:\Users\your_path_here_\WordFile.docx") ' open Word file
'copy third row of first Word table
WordDoc.Tables(1).Rows(3).Range.Copy
'paste in Excel
Range("A1").PasteSpecial xlPasteValues
WordDoc.Close 'close Word doc
WordApp.Quit ' close Word
End Sub
Or this.
Sub GetTables()
FName = Application _
.GetOpenFilename("Word Files (*.doc), *.doc")
Set WordObject = GetObject(FName)
First = True
RowCount = 2
For Each Tble In WordObject.tables
For i = 1 To 22
If First = True Then
Data = Tble.Rows(i).Cells(1).Range
'Remove cell markers
Cells(1, i) = Left(Data, Len(Data) - 2)
End If
Data = Tble.Rows(i).Cells(2).Range.Text
'Remove cell markers
Cells(RowCount, i) = Left(Data, Len(Data) - 2)
Next i
RowCount = RowCount + 1
First = False
Next Tble
WordObject.Close savechanges = False
End Sub
Using the code from the link How to preserve source formatting while copying data from word table to excel sheet using VB macro? , I've only been able to get the code to work when the macro pastes my Word table in a whole new separate workbook. When clicking a command button that's within the excel workbook that I want to import the Word table to, the table never pastes into the sheet called "Scraping Sheets" I've messed around with the code, but the closest thing I could get was placing the entire table into one cell with all formatting lost.
Private Sub CommandButton22_Click()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
Dim tbl As Object
FlName = Application.GetOpenFilename("Word files (*.Doc*),*.Doc*", , _
On Error Resume Next
Set oWordApp = GetObject(, "Word.Applicaton")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
Set oWordDoc = oWordApp.Documents.Open(FlName)
Set tbl = oWordDoc.Tables(1)
Dim wb As Workbook, ws As Worksheet
Set wb = Workbooks.Open(""C:\Users\xxxx\Desktop\292 Int'l_Weekly_Win_Loss_YYYY MM DD TEMPLATE.xlsm"")
Set ws = wb.Sheets("Scraping Sheet")
tbl.Range.Copy
ws.Range("A1").Activate
ws.Paste
MsgBox "Successfully Added File!"
End Sub

GetOpenFilename opens Dialogue box behind PowerPoint Presentation

I'm using VBA in powerPoint to update links to Excel Objects in my PowerPoint and everything is working well. The only Issue I have is that sometimes the Select File dialogue box opens behind the active Powerpoint and the only way to select it is to CTRL+ALT+Del and select the Excel File Chooser and set it as active. Is there a way to make it always be the active dialogue box when it opens? Here's the code I'm using:
Sub UpdateLinks()
Dim sld As Slide
Dim sh As Shape
Dim strNms As String
Dim intI As Integer
Dim strNewPath
Dim ExcelFile
Dim exl As Object
Set exl = CreateObject("Excel.Application")
'Set exl = exl.ActiveWindow
'exl.Active = True
'Open a dialog box to promt for the new source file.
ExcelFile = exl.Application.GetOpenFilename(, , "Select Excel File")
'Go through every slide
For Each sld In ActivePresentation.Slides
For Each sh In sld.Shapes
If sh.Type = msoLinkedOLEObject Then
With sh.LinkFormat
strNms = .SourceFullName
intI = InStr(1, strNms, "!")
strNewPath = ExcelFile & Mid(strNms, intI, Len(strNms) - intI + 1)
.SourceFullName = strNewPath
End With
End If
Next sh
Next sld
ActivePresentation.UpdateLinks
End Sub
Thanks.
Suggestion: try this version of a file picker instead:
Sub FileDialogExample()
' Courtesy of John Wilson
' www.pptalchemy.co.uk
Dim fd As FileDialog
Dim sFilename As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
.Filters.Add "Excel Files", "*.xls, *.xlsx"
.InitialFileName = Environ("USERPROFILE") & "\Desktop\"
.AllowMultiSelect = False
If .Show = True Then sFilename = .SelectedItems(1)
End With
'do whatever with sFilename
MsgBox "You picked " & sFilename
End Sub

Open File dialog box to get Excel

I've written some Word VBA which takes an Excel file and updates Labels (ActiveX Control) in the Word file. The only thing is this Excel file will change path and filename each month. Instead of editing 2 variables each month, how do I add an Open File dialog box so the user selects the Excel file to be used?
Here is what I have now:
Sub Update()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
PathWork = "C:\My Documents\2015-05 Report\"
CalcFile = "May2015-data.xlsx"
Set exWb=objExcel.Workbooks.Open(FileName:=PathWork & CalcFile)
ThisDocument.date.Caption=exWb.Sheets("Data").Cells(1,1)
End Sub
Here is a simplified macro which will allow the user to select only Macro-Enabled Excels. I couldn't comment on the previous answer as I have not earned enough reputation to comment on an answer. Please mind it.
Public Sub GetCaptionFromExcel()
Dim objExcel As New Excel.Application, exWb As Workbook
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select Macro-Enabled Excel Files"
.Filters.Add "Macro-Enabled Excel Files", "*.xlsm", 1
If .Show <> -1 Then Exit Sub
Set exWb = objExcel.Workbooks.Open(.SelectedItems(1))
'*** Use the values from excel here***
MsgBox exWb.Sheets("Data").Cells(1, 1)
'*** Close the opened Excel file
exWb.Close
End With
End Sub
You could try something like this
Replace PathWork and CalcFile with Dialogbox
With Dialogs(wdDialogFileOpen)
If .Display Then
If .Name <> "" Then
Set exWb = Workbooks.Open(.Name)
sPath = exWb.Path
End If
Else
MsgBox "No file selected"
End If
End With
Complete CODE should look like this
Option Explicit
Sub Update()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim sPath As String
'// Dialog box here to select excel file
With Dialogs(wdDialogFileOpen)
If .Display Then
If .Name <> "" Then
Set exWb = Workbooks.Open(.Name)
sPath = exWb.Path
End If
Set exWb = objExcel.Workbooks.Open(FileName:=sPath)
ActiveDocument.Date.Caption = exWb.Sheets("Data").Cells(1, 1)
Else
MsgBox "No file selected"
End If
End With
Set objExcel = Nothing
Set exWb = Nothing
End Sub

Resources