Follow

How can I add a legend to a Grapher graph using Scripter, where the legend entries are the X column headers?

This article contains a sample script for adding a legend to a graph in an existing Grapher plot, where each legend entry is tied to the plot's X column header.

To run this script:

  1. Click here to download the BAS file: NameLegendwithCells.BAS.
  2. Click Automation | Scripts | Run, select the BAS file from your downloads directory, and click Open.

OR:

  1. Copy the script below.
  2. Open Grapher and turn on the Script Manager by clicking View | Display | Script Manager.
  3. Press Ctrl+A to select all of the existing lines in the Script Manager and then press DELETE.
  4. Press Ctrl+V to paste it into the Script Manager.
  5. Click the Start/Resume icon () in the Script Manager.

 

*********

Sub Main
	Dim Grapher As Object
	Set Grapher = CreateObject("Grapher.Application")
	Grapher.Visible = True
	Set Doc1 = Grapher.Documents.Active
	i = 1
	While i < Doc1.Shapes.Count + 1
		If Doc1.Shapes.Item(i).Type = grfShapeGraph Then
			Set Graph1 = Doc1.Shapes.Item(i)
		End If
		i = i+1
	Wend

	'Add legend
	Set Legend = Graph1.AddLegend(True)

	'Link each entry to specific worksheet cell
	'Loop through each plot, getting the X column
	i = 1
	While i < Graph1.Plots.Count+1
		iCol = Graph1.Plots(i).yCol
		   'Convert the column number to a letter
		   iAlpha = Int((iCol-1) / 26)
		   iRemainder = iCol - (iAlpha * 26)
		   If iAlpha > 0 Then
				ConvertToLetter = Chr(iAlpha + 64)
		   End If
		   If iRemainder > 0 Then
			   ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
		   End If
		'Change the legend entry text to the right column and row
		Text1 = "<<@"+ConvertToLetter+"1>>"
		Legend.EntryName(i,Text1)
		i=i+1
		ConvertToLetter = ""
	Wend

	'Link legend entries to worksheet
	i=1
	While i < Legend.EntryCount+1
		Legend.EntryFont(i).worksheet = Graph1.Plots(1).worksheet
		i = i+1
	Wend

End Sub

 

Updated October 11, 2018

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.