I have a workbook with several sheets with data, which I'd like to export as PDF. That step is pretty simple to achieve with the following code :
Sub ExportAsPDF()
Dim FolderPath As String
FolderPath = "C:\Output_folder"
Sheets(Array(1, 2)).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & "\Test", _
IncludeDocProperties:=True, OpenAfterPublish:=True, IgnorePrintAreas:=False
End Sub
However, to this export I would also like to add a chart object which is in another sheet, let's say sheet 3 (only the chart object, not the whole sheet).
I have tried adding the chart to the selection, right after Sheets(Array1,2)).Select :
Sheets(3).ChartObjects(1).Activate
ActiveChart.ChartArea.Select
But obviously this does not work and the PDF now only contains the chart object without the content of the sheets 1 & 2.
How should I proceed to export into one PDF both the content of sheets and a specific chart object ?
Many thanks for your inputs. I couldn't find any related question that mixes two types of objects (sheet and charts) for one export.
Kind regards
Related
I have a bunch of cells that I won't to get the html representation of.
From the post Export specific range into an HTML I use the answer to save an html representation to a file, but is there a way to output it to a variable instead?
My final use of this html does not except classes in the html so I need to search and replace text within the output before I can use it.
Is there a way to change the output of the following code from a file to a variable?
Sub Export()
Dim rng As Range
file1 = ThisWorkbook.Path & "\" & "test.html"
Set rng = Sheets("Tabelle1").Range("A1:C10")
ActiveWorkbook.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=file1, _
Sheet:=rng.Worksheet.Name, _
Source:=rng.Address, _
HtmlType:=xlHtmlStatic).Publish
End Sub
The content of your sheet's range is already stored in the rng object variable, hence, all of its information is there, it will prevail as long as you like in the code, why would you add another variable to it?
I made the code to convert the values to the csv file but the problem is
that I'm not sure if this is the right way because this is the first time I even touched VBA macro! As seen in the image I provided, there is a button "Convert to CSV", when I tap it, the macro will call ExportWorksheetAndSaveAsCSV method and will convert the entire sheets contents into csv. However, it looks like it converts the entire sheet it'self.
What I want to do is the following steps .
1.Pass in the Sheet name as a parameter like ExportWorksheetAndSaveAsCSV("Sheet2"), so that it can be used as a file name. But I'm not sure how I can pass a parameter in function from the Buttton.
2.Convert the values in the columns E to I to CSV. If possible want to have the tites of the data show in the first row of the csv file.
I attached the image and the code so you can see. Some tips or examples will be really helpful! I would love to hear from you.
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Dim book As String
Dim fileName As String
book = "Sheet1"
fileName = "test.csv"
Set shtToExport = ThisWorkbook.Worksheets(book) 'Export to CSV file
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False
wbkExport.SaveAs fileName:="C:\Users\myStuff\Documents\" & fileName, FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
I have data in excel sheet like this
Country Product Price
America A 43
China B 13
Germany C 21
Turkey D 12
In excel i select this data and make a chart out of it that seems like this
But the problem is when i select the same data with vba and draw the chart from vba then it results into
Now i want the vba chart to display to category axis as same as we select data from excel and draw the chart.
In short i want the vba chart to automatically adjust according to the data.
Here is the code.
Sub CreateChart()
Range("a1").Select
Selection.CurrentRegion.Select
myrange = Selection.Address
mysheetname = ActiveSheet.Name
Worksheets(1).Activate
'ActiveWindow.DisplayGridlines = False
' Add a chart to the active sheet.
ActiveSheet.ChartObjects.Add(125.25, 60, 301.5, 155.25).Select
Application.CutCopyMode = False
ActiveChart.ChartWizard _
Source:=Sheets(mysheetname).Range(myrange), _
Gallery:=xlColumnStacked, Format:=10, PlotBy:=xlRows, _
CategoryLabels:=1, SeriesLabels:=1, HasLegend:=1, _
Title:=charttitle, CategoryTitle:=chartcategory, _
ValueTitle:=chartvalue, ExtraTitle:=""
End Sub
It's very simple in Excel. Record a macro while inserting the chart and selecting the data for the chart. The recorder records the VBA steps and gives you the neat code which can do the same whenever you execute. For instance, the recorder gave me this 2 lines of code:
Sub Macro1()
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("A2:C5"), PlotBy:=xlColumns
End Sub
Pretty simple, isn't it?
If you just wana to update data in already existing chart, better solution can be to update them. Basicaly create chart which you desire and assign some name to it. (for example myLovelyChart)
Sub updateChartSO()
Dim chartSheet As Worksheet
Set chartSheet = Sheets("testSheet")
Dim chtSerie As Series
With chartSheet
For Each chtSerie In .ChartObjects("myLovelyChart").SeriesCollection
'specify your values, can be specified by array or even from sheet'
chtSerie.Values = ""
chtSerie.XValues = ""
Next
End With
End Sub
Or if you really wana to create new chart, take a closer look at chartType property (https://msdn.microsoft.com/en-us/library/office/ff820803.aspx) and its enumeration (https://msdn.microsoft.com/en-us/library/office/ff838409.aspx)
In VBA, it auto define the format based on data range.
However, You can using below code to control it
Chart(1).PlotBy = xlRows
OR
Chart(1).PlotBy = xlColumns
I have a small tool to export the pictures inside ppt documents to image files, so I can import them somewhere else.
For this, I have been using the following piece of code:
For Each slideShape In slide
If slideShape.Type = msoPicture Then
Call slideShape.Export(materialPresentation.Path & "\" & ecode & "_" & cont & ".jpg", ppSaveAsJPG)
cont = cont + 1
End If
Next slideShape
However, in a different tool, I am required to export all the shapes of a slide at once, exactly like selecting them with the mouse, and clicking in "Save as image", which creates an image with all the shapes.
Is there a way to do it using VBA? All I found online were examples of exporting single shapes (Which I already know).
Group the shapes you want to export then export the resulting group shape.
What may also work is exporting via ShapeRange (slide is a Slide object), e.g.
slide.Shapes.Range().Export("C:\output.jpg", ppShapeFormatJPG)
Q1: The routine below does not work.
Sub test()
TXT = Sheets("INDEX").Cells(2, 1).Value
AKO = Sheets("TOBESEEN").Cells(1, 1).Address
Sheets("INDEX").Hyperlinks.Add Anchor:=Sheets("INDEX").Cells(1, 2), Address:="",
SubAddress:=AKO, TextToDisplay:=TXT
End Sub
Q2. Is there a place where I can see ALL the properties of the cell? When I type the "dot" after cells, VBA DOES NOT GIVE any options.
Like
sheet1.cell(1,2).VALUE
sheet1.cell(1,2).ADDRESS
sheet1.cell(1,2).?
I suspect my problem is related to the definition of AKO, but I am not sure what the correct property is (if not ADDRESS)
Thank you
Q1: Try to use this code:
Sub test()
TXT = CStr(Sheets("INDEX").Cells(2, 1).Value)
AKO = Sheets("TOBESEEN").Cells(1, 1).Address
Sheets("INDEX").Hyperlinks.Add _
Anchor:=Sheets("INDEX").Cells(1, 2), _
Address:="", _
SubAddress:=Sheets("TOBESEEN").Name & "!" & AKO, _
TextToDisplay:=TXT
End Sub
Q2: you can use F2 help. There you can see a list of properties and methods of any object.
When you create a hyperlink in a document, you need to give the "full" address of the cell you are linking to (sheet name and cell address), not just the .Address (which is the absolute address on a given sheet, but doesn't include the sheet information). To get the full address (including the sheet) of a cell, you need to add an additional parameter to the Address():
.Address(External:=True)
which will give you the full address, including workbook and sheet name. Unfortunately, if you create this link and then change the name of the workbook (maybe because you had not saved it up to this point), the link will break.
It is therefore (slightly) more robust to create a link that doesn't include the workbook name. The following routine does this for you. Note that is usually a good idea to split your code into small self-contained functions that do one thing particularly well - you can re-use your code more easily, and the main program becomes easier to read and maintain. I suggest therefore that you create the following function:
Sub addLink(target As Range, location As Range, text As String)
' create a hyperlink with text "text"
' in the cell "location"
' pointing to the range "target"
Dim linkAddress As String
linkAddress = target.Address(external:=True) ' this is the "full" address
'remove everything between brackets - this is the workbook name:
bLeft = InStr(1, linkAddress, "[") ' location of left bracket
bRight = InStr(bLeft, linkAddress, "]") ' location of right bracket
linkAddress = Left(linkAddress, bLeft - 1) + Mid(linkAddress, bRight + 1)
' now create the link:
location.Parent.Hyperlinks.Add _
anchor:=location, _
Address:="", _
SubAddress:=linkAddress, _
TextToDisplay:=text
End Sub
You can call this from your code above as follows:
Dim TXT As String, AKO As Range, LOC As Range ' define types when possible
TXT = Sheets("INDEX").Cells(2, 1).Value ' I called this text
Set AKO = Sheets("TOBESEEN").Cells(1, 1) ' I called this target (note - need Set)
Set LOC = Sheets("INDEX").Cells(1, 2) ' I called this location
addLink AKO, LOC, TXT
As for the second part of your question - "I can't see the properties of Cells()". Yes, that is annoying. It happens that Cells() is a lot like a Range object; you can see in the above that I was able to do Set AKO = Sheets("TOBESEEN").Cells(1,1) which demonstrates this. You can declare a variable as being of the type Range, and then tooltips will work for you:
Dim r As Range
r.
and as you type r. you will see a list of the properties of Range (which are also the properties of Cells):
It is annoying that Cells doesn't just do this by itself. It is annoying that Address() doesn't have an option to include the sheet name and not the workbook name. Excel is full of annoyances. In fact, there is even a book called "Excel Annoyances". And more could be written, I'm sureā¦
At least there are usually VBA tricks to work around these things and get the job done.