Excel Script - AutoFit Column Width

Hello All,

I have written a simple script that will adjust the column widths in excel to adjust to the longest cell value. I was wondering if anyone had a way to do this without using system events.

Thanks,
CarbonQuark


tell application "Microsoft Excel"
	activate
	tell application "System Events"
		keystroke "a" using command down
	end tell
	tell application "System Events"
		tell process "Microsoft Excel"
			tell menu bar 1
				tell menu bar item "Format"
					tell menu "Format"
						tell menu item "Column"
							tell menu 1
								click menu item "AutoFit Selection"
							end tell
						end tell
					end tell
				end tell
			end tell
		end tell
	end tell
end tell

This works for Excel 2004 -


tell application "Microsoft Excel"
	tell active sheet
		--enter your own custom range values like this:
		autofit column "A:D"
		--OR this for all columns:
		autofit columns
	end tell
end tell

Mark

Also if you wanted to shorten your code, but still use GUI scripting you can do this.

tell application "System Events"
	tell process "Excel"
		click menu item "AutoFit Selection" of menu 1 of menu item "Column" of menu 1 of menu bar item "Format" of menu bar 1
	end tell
end tell

Thanks for the fast responses guys,

Both will work! Just what I was looking for!

CarbonQuark