I have an Excel file that contains data and charts. I've created a macro to read in a text file and update the data and the chart data ranges based on the date in the excel file. The data range will be starting 5 day prior to the date in the text file up to the date.
This works perfectly in Excel but now what I would like the macro to do is open a PowerPoint file I've already created that contains the two charts linked to the Excel file and change the data range of the Excel chart in the PowerPoint presentation.
I am able to open the PowerPoint and select the graph by name but I cannot change the data range.
Here is the code I am using currently that is not working but also not throwing any errors...
Open the PowerPoint and set the global oPPT variable to the open presentation.
Public Sub Open_PowerPoint_Presentation()
'Opens a PowerPoint Document from Excel
Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True
Set oPPTFile = objPPT.Presentations.Open(FileName:=ActiveWorkbook.Path & "\DailyHealthCheck.pptx")
End Sub
Call the routine above, change dates on some labels, and then attempt to change the source data of the Excel.
' open the gd metrics power point, must be manually closed later
Open_PowerPoint_Presentation
' set the dates in the ppt slide to the current date
oPPTFile.Slides(1).Shapes("Low Left Date").TextFrame.TextRange.Text = Format(Now, "MMMM d, yyyy")
oPPTFile.Slides(1).Shapes("Critical Issues Table").Table.Cell(1, 1).Shape.TextFrame.TextRange.Text = "Grid Director Critical Issues (as of " & Format(Now, "M/d") & ")"
' change the date ranges of the chart
If ppdRangeStr <> "" Then
Dim splitDateRange() As String
splitDateRange = Split(ppdRangeStr, ":")
ppdRangeStr = "='process per day'!$" & Left(splitDateRange(0), 1) & "$" & Right(splitDateRange(0), Len(splitDateRange(0)) - 1) & ":$" & Left(splitDateRange(1), 1) & "$" & Right(splitDateRange(1), Len(splitDateRange(1)) - 1)
MsgBox ppdRangeStr
oPPTFile.Slides(1).Shapes("Processed Per Day Chart").Chart.SetSourceData Source:=ppdRangeStr, PlotBy:=xlColumns
' reset data labels
oPPTFile.Slides(1).Shapes("Processed Per Day Chart").LinkFormat.Update
End If
The String ppdRangeStr is "'processed per day'!$H77:$G81" which is the same range the chart in the Excel file (which works) is using.
Does anyone know how I can make the macro in the Excel file change the source data of the Excel chart in the PowerPoint where the source data is in the Excel file? (If that make sense?)
Related
Hi this is a follow up question from my previous question: Insert text to Word from Excel looping through drop down list
In addition to inserting text, I need to insert graphs for every region and copy the graph under each text. The graphs changes with the data for every region and is located next to the data table.
So the result has to look like this:
Text 1
Graph 1
Text 2
Graph 2 etc.
The code that inserts text (see from the previous question):
Sub Export()
Dim reg As Variant, col As String, txt As String
With ThisWorkbook.Sheets("Sheet 1")
For Each reg In Array("Region1", "Region2", "Region3")
.Range("B3") = reg
.Calculate
col = IIf(.Range("D2").Value = 14, "C", "D") 'select column due to D2 value
' collect all texts in txt
txt = txt & vbTab & "For " & reg & ", on June, 21 the estimate was " & _
.Range(col & "6").Text & " and the volume was " & .Range(col & "7").Text & _
" and the variance was " & .Range(col & "8").Text & vbLf
Next
End With
With CreateObject("Word.Application").Documents.Add
.Range.Text = txt ' output all text to the document
.SaveAs "C:\temp\AllTheText.docx" ' your path and name
.Parent.Quit 'quit Word
End With
End Sub
Sorry this isn't a bonafide answer, I don't have the reputation to ask a follow up question...
Have you considered copying the chart from Excel into Word, then issuing a Refresh command on the chart in Word once data is updated in Excel? You could then create a "AlltheTextTemplate" Word file with the charts preset. You'd then just create a copy of the template when creating a new report, fill it in with the data, and create a small bit of code to refresh the chart object.
Here's a few lines you could add:
Set wordapp = CreateObject("Word.Application")
' Path listed here assumes the template is stored in the same DIR as the workbook
Set objDoc = wordapp.documents.Open(Application.ThisWorkbook.Path & "\Template.docx")
wordapp.Visible = True 'Remove if you don't need to see it
With ObjDoc
.Range.Text = txt ' output all text to the document
.InlineShapes(1).LinkFormat.Update 'update the shape ID as needed
.InlineShapes(1).LinkFormat.BreakLink 'If you want to break the data link
.SaveAs "C:\temp\AllTheText.docx" ' your path and name
.Parent.Quit 'quit Word
End With
The following code is intended to update Word bookmarks with formatted data from Excel, however the formatting doesn't come across and unsure why, would appreciate any suggestions. The formatted data is text with certain works underlined.
Set wb = ActiveWorkbook
TodayDate = Format(Date, "mmmm d, yyyy")
Path = wb.Path & "\update_file.docx"
'Create a new Word Session
Set pappWord = CreateObject("Word.Application")
'Open document in word
Set docWord = pappWord.Documents.Add(Path)
'Loop through names in the activeworkbook
For Each xlName In wb.Names
'if xlName's name is existing in document then put the value in place of the bookmark
If docWord.Bookmarks.Exists(xlName.Name) Then
docWord.Bookmarks(xlName.Name).Range.Text = Range(xlName).Text
End If
Next xlName
Try this instead, using Copy and the (poorly-documented) ExecuteMso method. You need to use Copy against the range (in order to capture formatting) and then you can effectively do the same as the right-click Paste + Keep Source Formatting option:
If docWord.Bookmarks.Exists(xlName.Name) Then
xlName.RefersToRange.Copy
docWord.Bookmarks(xlName.Name).Select
docWord.Application.CommandBars.ExecuteMso "PasteSourceFormatting"
End If
Alternatively, and this might be better because ExecuteMso is asynchronous and can result in timing issues:
xlName.RefersToRange.Copy
docWord.Bookmarks(xlName.Name).Range.PasteAndFormat 16 'wdFormatOriginalFormatting
In management having and updating a deck of 150 slides is hard, when automation does not work. On Windows you can easily update numbers in Excel and Connected Graphs (Link to source data) change.
I don't know if anyone wondered, but it seems a long known issue:
To paint on the picture, to make clear what I want to achieve with my coding, here the rest of the story: In our company, there are coming all kind of systems together. I am using a Mac (and Office Mac), while others request the same data and working it with Office Windows. As I found out its the Apple system's arangement that disable many functions of MSO Programms or automation. I tested this automatic update story with a Office on Windows and Mac and did the following steps:
Created an Excel file and put in some numbers
Made a graph from that.
"Special-pasted" the graph in a new Powerpoint file (with link to data source - no here is not a mistake)
Changed numbers in Excel and it updated the graph in Powerpoint.
Saved and closed both files in one folder. (and did not change the path of course)
Opened the Excel again, changed data and opened Powerpoint (comparing Office Windows and Office Mac)
Office Windows: Powerpoint asked me to update all linked data. Data updated
Office Mac: did not ask anything. Data not updated.
So this is only the description of the bigger problem. To solve that issue (that may only be fixed in years... its been a long known issue already) I am trying to use VBA.
In the code I differenciate between Windows and Mac, finally there should be one code for all users. What I did so far:
run a code depending on the operating system (Mac is the problem!!)
copy range
create chart
paste range into chart
save chart as image
--> here I have problems, as saved files on Mac are empty (0 bytes).
NOTE: My example excel is hold easy and contains 3 sheets: UKI, France and Pictures. UKI and France are example sheets with numbers and graphs, created from those. The graphs' range is copied and used to copy - one by one - into pictures. The aim is to copy a chart, save it - and repeat this for each country area (eg. UKI France).
Where I am struggling is the export part. On Mac files normally are saved in a special microsoft folder ..../users/.../microsoft.com/data/......
When I try to adress "special folders"; such as desktop, pictures, documents (etc.) I receive an error message saying "permission denied". Here the Apple Sandbox Requirements seem to block me off.
Only the special folder "pictures" seem to work: saved files appear, but just like in the microsoft folder they are created empty.
I am new to VBA, so this i probably a mess of a code -
but why are the saved jpg/jpeg. files empty (also other picture-formats are empty)??
My Coding so far: (May be out of position a bit)
Sub TakePictures()
'check for running system; then play script for Mac or Windows
#If Mac Then
'I am a Mac
MsgBox "Call your Mac_Macro"
MsgBox "Call your Mac_Macro"
Dim i As Integer
Dim intCount As Integer
Dim objPic As Shape
Dim objChart As Chart
'UKI
'copy the range as an image
Call Worksheets("UKI").Range("D1:I14").CopyPicture(xlScreen, xlPicture)
'remove all previous shapes in sheet2
intCount = Worksheets("Picture").Shapes.Count
For i = 1 To intCount
Worksheets("Picture").Shapes.Item(1).Delete
Next i
'create an empty chart in sheet2
Worksheets("Picture").Shapes.AddChart
'activate sheet2
Worksheets("Picture").Activate
'select the shape in sheet2
Worksheets("Picture").Shapes.Item(1).Select
Set objChart = ActiveChart
'paste the range into the chart
Worksheets("Picture").Shapes.Item(1).Line.Visible = msoFalse
Worksheets("Picture").Shapes.Item(1).Width = Range("D1:I14").Width
Worksheets("Picture").Shapes.Item(1).Height = Range("D1:I14").Height
objChart.Paste
' Call AppleScript to get a special folder
Dim NameFolder As String
Dim SpecialFolder As String
' You can use : home, documents, desktop, music, pictures, movies, applications
NameFolder = "documents"
If Int(Val(Application.Version)) > 14 Then
SpecialFolder = _
MacScript("return POSIX path of (path to " & NameFolder & " folder) as string")
'Replace line needed for the special folders Home and documents
SpecialFolder = _
Replace(SpecialFolder, "/Library/Containers/com.microsoft.Excel/Data", "")
Else
SpecialFolder = MacScript("return (path to " & NameFolder & " folder) as string")
End If
Dim fileAccessGranted As Boolean
Dim filePermissionCandidates
'Create an array with file paths for which permissions are needed_
'filePermissionCandidates = Array("/Users/<user>/Desktop/test1.txt", "/Users/<user>/Desktop. /test2.txt")
'Request Access from User_
'fileAccessGranted = GrantAccessToMultipleFiles(filePermissionCandidates)
'save the chart as a JPEG
Dim LoginName As String
LoginName = UCase(GetUserID)
'ChDir "C:\Users\" & LoginName & "\Specialfolder"\"
Debug.Print LoginName
'objChart.Export ("C:Users\" & LoginName & "\documents\FY1718_UKI.jpg")
objChart.Export ("/Users/fabianvoss/pictures/FY1718_UKI.pdf")
'*here the export does give me empty files - tested out already all different kind of different data types.
#Else
'I am Windows
MsgBox "Call Windows_Macro"
'Activeselection.Export Filename:="D:\FY1718_UKI.jpg", Filtername:="JPG"
'Existiert Bild-Ordner unter Laufwerk C? -> Abfrage mit if:
'Wenn ja: Weiter
'Sonst: erstellen, dann weiter
On Error Resume Next
MkDir "C:\VBATestBilder"
On Error GoTo 0
'Neues Sheet erstellen: "Picture"
Dim i As Integer
Dim intCount As Integer
Dim objPic As Shape
Dim objChart As Chart
'UKI
'copy the range as an image
Call Worksheets("UKI").Range("D1:I14").CopyPicture(xlScreen, xlPicture)
'remove all previous shapes in sheet2
intCount = Worksheets("Picture").Shapes.Count
For i = 1 To intCount
Worksheets("Picture").Shapes.Item(1).Delete
Next i
'create an empty chart in sheet2
Worksheets("Picture").Shapes.AddChart
'activate sheet2
Worksheets("Picture").Activate
'select the shape in sheet2
Worksheets("Picture").Shapes.Item(1).Select
Set objChart = ActiveChart
'paste the range into the chart
Worksheets("Picture").Shapes.Item(1).Line.Visible = msoFalse
Worksheets("Picture").Shapes.Item(1).Width = Range("D1:I14").Width
Worksheets("Picture").Shapes.Item(1).Height = Range("D1:I14").Height
objChart.Paste
'save the chart as a JPEG
objChart.Export ("C:\VBATestBilder\FY1718_UKI.Jpeg")
'FRANCE
'copy the range as an image
Call Worksheets("France").Range("D1:I14").CopyPicture(xlScreen, xlPicture)
'remove all previous shapes in sheet2
intCount = Worksheets("Picture").Shapes.Count
For i = 1 To intCount
Worksheets("Picture").Shapes.Item(1).Delete
Next i
'create an empty chart in sheet2
Worksheets("Picture").Shapes.AddChart
'activate sheet2
Worksheets("Picture").Activate
'select the shape in sheet2
Worksheets("Picture").Shapes.Item(1).Select
Set objChart = ActiveChart
'paste the range into the chart
Worksheets("Picture").Shapes.Item(1).Line.Visible = msoFalse
Worksheets("Picture").Shapes.Item(1).Width = Range("D1:I14").Width
Worksheets("Picture").Shapes.Item(1).Height = Range("D1:I14").Height
objChart.Paste
'save the chart as a JPEG
objChart.Export ("C:\VBATestBilder\FY1718_France.Jpeg")
'Delete new chart
#End If
End Sub
I dont get why the files on Mac are created but empty... ?
(Then, if files can be saved, I need to import them to Powerpoint to very different positions on different slides (on Windows its easy, on Mac maybe difficult))
Thank you for reading,
I would appreciate any help
PS: I am completely new to VBA
regards,
Fabian
Someone asked this question: How do I create form controls (radio, checkbox, buttons, etc.) in Excel using Apache POI (Java)? before but no answers yet.
Also is it possible to make certain rows read only?
No not as far as i know, but you can create an Excel file with checkboxes that you can read back into Java using POI in this fashion:
Create an Excel file and save as template.xlsm (so with macro's).
Insert VBA macro in the Excel file (use 'Developer' tab) and save + close the file:
Sub addCheckBoxes()
Dim i As Integer
Dim cel As Range
i = 2
For Each cel In Sheets("Sheet1").Range("A" & 3 & ":A" & 1000)
i = i + 1
If Cells(i, "B").Value <> "" Then
cel.Value = 0
With ActiveSheet.OLEObjects.Add(ClassType:="Forms.CheckBox.1", Left:=cel.Left, Top:=cel.Top, Width:=cel.Width, Height:=cel.Height)
.LinkedCell = "Sheet1!$A$" & i
.Object.Caption = "<-use"
End With
End If
Next
End Sub
Let POI read this excel file as a new Workbook:
Workbook wb = WorkbookFactory.create(new File("path to your file/template.xlsm"));
Write all your data to the file (keep Column A empty for this example !). In this example we will add a checkbox to all cells in column 'A' that have a value/text in column 'B'. It checks every row from row 3 till 1000.
Write the Workbook to file:
FileOutputStream out = new FileOutputStream("path to your file/file_with_checkboxes.xlsm");
Create a file: start_excel_file.vbs add add the code as text:
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("path to your file/file_with_checkboxes.xlsm")
objExcel.Application.Visible = True
objExcel.Application.Run "file_with_checkboxes.xlsm!addCheckBoxes"
Use Java to open the file through the command line by running this file: start_excel_file.vbs
The code in the start_excel_file.vbs file will open the excel file and at start up it will create the checkboxes using the addCheckBoxes() Macro. (Macro's must be enabled !)
In this code i created a boolean text that is not visible in the Excel file but will be set to TRUE if selected and FALSE is unselected afterwards. If you read the file with POI back into Java it will ignore the checkboxes but is able to read the boolean text so in Java you know what was/is the setting. (empty or FALSE = false / TRUE is true)
hope this helps and good luck =^)
I have an Access db to track metrics and "number crunch" data to build PowerPoint presentations. I do about 40 presentations per month, and they are 98% charts.
I run queries one at a time (using SQL statements), take the resulting data and copy it into an Excel template (I made a mock table in this "template" so the chart is already built and formatted), then copy the chart as a picture into a PowerPoint template.
So there is a lot of manual work.
How can I run multiple queries in Access with VBA on the same dataset/table (I have to do sales by quarter, by month, by region, by state, by site and all of these are Top5 aggregate, hence the reasons for the charts), and then send the resulting data to a specific Excel workbook, while defining what goes into what cell range?
If I get all the data into Excel, and have the charts ready to go, is there some VBA that will take the charts from Excel (activeworksheet) and paste them into PowerPoint as pictures in a quad view layout?
Can I do the same thing with an Access to PowerPoint approach and cut out Excel?
I am a novice at best.
You don't need to use Excel at all ! Use MS Access Charts in a report and some VBA code to put them into Powerpoint directly. There is already an example here
One "gotcha" is if you generate graphs in a group ie you design the report with a graph that is inside a group - so when you run the report you will get numerous graphs created.
It is a bit tricky to get hold of each of these graphs and drop them into Powerpoint but here is some code that will take care of it. This works in Access 2003
'Loop through all the controls in this report and pickout all the graphs
For Each c In pReport.Controls
'Graphs initially appear to be in an Object Frame
If TypeOf c Is ObjectFrame Then
'Check the Class of the object to make sure its a Chart
If Left$(c.Class, 13) = "MSGraph.Chart" Then
'Check if this graph must be cloned (required if the graph is in a group in the MS Access report)
If Not IsGraphToBeCloned(pReport.Name, c.ControlName) Then
InsertGraphToPptSlide c, "", pReport.Name
Else
InsertGraphGroupToPpt pReport.Name, c
End If
End If
End If
Next
This will find all the graphs in the report, if the graph is in a group then we call the InsertGraphGroupToPPt function.
The trick here is that we know we have the same base graph multiple times - but populated with different data. So in Powerpoint what you need to do is paste the base graph into powerpoint slides n times - where n is the number of groups and then update the graphs query properties
eg
Function UpdateGraphInPowerpoint(sql As String, OrigGraph As ObjectFrame, Groups As dao.Recordset, GroupName As String, ReportName As String) As Boolean
//Copyright Innova Associates Ltd, 2009
On Error GoTo ERR_CGFF
On Error GoTo ERR_CGFF
Dim oDataSheet As DataSheet
Dim Graph As Graph.Chart
Dim lRowCnt, lColCnt, lValue As Long, CGFF_FldCnt As Integer
Dim CGFF_Rs As dao.Recordset
Dim CGFF_field As dao.Field
Dim CGFF_PwrPntloaded As Boolean
Dim lheight, lwidth, LLeft, lTop As Single
Dim slidenum As Integer
Dim GraphSQL As String
Dim lGrpPos As Long
'Loop thru groups
Do While Not Groups.EOF
'We want content to be added to the end of the presentation - so find out how many slides we already have
slidenum = gPwrPntPres.Slides.Count
OrigGraph.Action = acOLECopy 'Copy to clipboard
slidenum = slidenum + 1 'Increment the Ppt slide number
gPwrPntPres.Slides.Add slidenum, ppLayoutTitleOnly 'Add a Ppt slide
'On Error Resume Next 'Ignore errors related to Graph caption
gPwrPntPres.Slides(slidenum).Shapes(1).TextFrame.TextRange.Text = ReportName & vbCrLf & "(" & Groups.Fields(0).Value & ")" 'Set slide title to match graph title
gPwrPntPres.Slides(slidenum).Shapes(1).TextFrame.TextRange.Font.Size = 16
gPwrPntPres.Slides(slidenum).Shapes.Paste 'Paste graph into ppt from clipboard
Set Graph = gPwrPntPres.Slides(slidenum).Shapes(2).OLEFormat.Object
Set oDataSheet = Graph.Application.DataSheet ' Set the reference to the datasheet collection.
oDataSheet.Cells.Clear ' Clear the datasheet.
GraphSQL = Replace(sql, "<%WHERE%>", " where " & GroupName & " = '" & Groups.Fields(0).Value & "'")
Set CGFF_Rs = ExecQuery(GraphSQL)
CGFF_FldCnt = 1
' Loop through the fields collection and get the field names.
For Each CGFF_field In CGFF_Rs.Fields
oDataSheet.Cells(1, CGFF_FldCnt).Value = CGFF_Rs.Fields(CGFF_FldCnt - 1).Name
CGFF_FldCnt = CGFF_FldCnt + 1
Next CGFF_field
lRowCnt = 2
' Loop through the recordset.
Do While Not CGFF_Rs.EOF
CGFF_FldCnt = 1
' Put the values for the fields in the datasheet.
For Each CGFF_field In CGFF_Rs.Fields
oDataSheet.Cells(lRowCnt, CGFF_FldCnt).Value = IIf(IsNull(CGFF_field.Value), "", CGFF_field.Value)
CGFF_FldCnt = CGFF_FldCnt + 1
Next CGFF_field
lRowCnt = lRowCnt + 1
CGFF_Rs.MoveNext
Loop
' Update the graph.
Graph.Application.Update
DoEvents
CGFF_Rs.Close
DoEvents
Groups.MoveNext
Loop
UpdateGraphInPowerpoint = True
Exit Function
End Function
Since you are a novice, perhaps you should break the task down into parts and automate the parts one at a time. Each step will provide benefits (i.e. time savings) and you can learn as you go.
It is hard to make specific recommendations based upon lack of specific information (what version etc.). That having been said, perhaps a good first step would be to link the Excel tables to the access queries so that the spreadsheets can auto-update every month and you will not have to cut and paste data from Access into Excel. You can do this linking entirely within Excel.
If you are using Excel 2007 click on "Data" in the Ribbon and then click on "From Access".
What you're asking is a lot of work:
Via VBA you'd have to open Excel (Excel Application manipulation from Access) , update your charts (Range manipulation, Data Update) if you have the rights then I would suggest having your pivot charts connected to the Access data and not pasted into the workbook, nevertheless I've been in enough situations where that was not possible. Then you would have to open your PowerPoint presentation and copy from the Excel to the PowerPoint. I've done all of these and know how much work it can save by creating a macro (via VBA) to do this. It's a lot of code.