2

How do I change the axis type of an Excel chart's X axis using PowerShell?

To do this manually using Excel:

  • open workbook in Excel
  • select X axis chart
  • select "Axis options"
  • configure "Text axis" under the "Axis Type" option

Update: it's XLSX format. I should clarify: the issue is that the data set I'm plotting uses dates on the x axis and Excel is intelligently filling in the gaps (so if I have May 5 and May 7 in the data set, Excel plots May 6 too). Swapping to Text appears to fix this issue in the Excel app. I wish to automate this like the rest of my data analysis and charting.

2
  • 1
    What format, XLS or XLSX? Commented Apr 20, 2016 at 16:30
  • @Taosique please see the question update. Thanks. Commented Apr 21, 2016 at 8:05

1 Answer 1

7
+300

There you are:

# Launch Excel:
$app = New-Object -comobject Excel.Application

# Open a Workbook:
$app.Workbooks.Open("C:\Users\admin\Desktop\Workbook.xlsx")

# Activate the chart you need (note: you don't need full path with filename now):
$app.Workbooks("Workbook.xlsx").Sheets("Sheet1").ChartObjects("Chart 1").Activate()

# Change the category type of axis. Axes(1) means category axis. Possible values:
# xlCategoryScale = 2
# xlTimeScale = 3
# xlAutomaticScale = -4105
$app.ActiveChart.Axes(1).CategoryType = 2

# Save & close the workbook
$app.Workbooks("Workbook.xlsx").Close($True)

You can now return to step 2, open another workbook and repeat these actions. After you're done, close the Excel application and clean up:

$app.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($app)
Remove-Variable app
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for both the answer and the last bit that releases the ComObject. I suspect you'll say experience but may I ask what documentation you used, e.g. to find out the TimeScale value or the Axes(1) meaning?
I used these references: msdn.microsoft.com/en-us/library/… msdn.microsoft.com/en-us/library/… .To find values, I used Excel VBA editor: stepped on breakpoint and added watch for xlCategory to see it equals 1. Also its a good way to find what VBA code you need by recording a macro, doing things manually in Excel and then looking at the code it generates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.