Setting Horizontal and Vertical Excel cell alignment with AutoHotkey

Excel cell alignment with AutoHotkey

Excel cell alignment with AutoHotkey

I love how easy it is to use AutoHotkey to set Excel formatting.   The below AutoHotkey syntax and video show how easy it is to set both vertical and horizontal alignment within Excel.  It also introduces the concepts of Excel Constants.

 
; Excel cell alignment with AutoHotkey
XL_Handle(XL,1) ;get handle to Application
;~ XL_Format_HAlign(XL,RG:="A1:C1",h:=1) ;1=Left 2=Center 3=Right
XL_Format_VAlign(XL,RG:="A1:C1") ;1=Top 2=Center 3=Distrib 4=Bottom

XL_Format_HAlign(PXL,RG="",h="1"){ ;defaults are Right bottom
IfEqual,h,1,Return,PXL.Application.ActiveSheet.Range(RG).HorizontalAlignment:=-4131 ;Left
IfEqual,h,2,Return,PXL.Application.ActiveSheet.Range(RG).HorizontalAlignment:=-4108 ;Center
IfEqual,h,3,Return,PXL.Application.ActiveSheet.Range(RG).HorizontalAlignment:=-4152 ;Right
}
; Excel cell alignment with AutoHotkey
XL_Format_VAlign(PXL,RG="",v="1"){
IfEqual,v,1,Return,PXL.Application.ActiveSheet.Range(RG).VerticalAlignment:=-4160 ;Top
IfEqual,v,2,Return,PXL.Application.ActiveSheet.Range(RG).VerticalAlignment:=-4108 ;Center
IfEqual,v,3,Return,PXL.Application.ActiveSheet.Range(RG).VerticalAlignment:=-4117 ;Distributed
IfEqual,v,4,Return,PXL.Application.ActiveSheet.Range(RG).VerticalAlignment:=-4107 ;Bottom
}

;  Function for connecting to Excel
XL_Handle(ByRef PXL,Sel){
ControlGet, hwnd, hwnd, , Excel71, ahk_class XLMAIN ;identify the hwnd for Excel
IfEqual,Sel,1, Return, PXL:= ObjectFromWindow(hwnd,-16).application ;Handle to Excel Application
IfEqual,Sel,2, Return, PXL:= ObjectFromWindow(hwnd,-16).parent ;Handlle to active Workbook
IfEqual,Sel,3, Return, PXL:= ObjectFromWindow(hwnd,-16).activesheet ;Handle to Active Worksheet
}
;***********adapted from ACC.ahk*******************
ObjectFromWindow(hWnd, idObject = -4){
(if Not h)?h:=DllCall("LoadLibrary","Str","oleacc","Ptr")
 If DllCall("oleacc\AccessibleObjectFromWindow","Ptr",hWnd,"UInt",idObject&=0xFFFFFFFF,"Ptr",-VarSetCapacity(IID,16)+NumPut(idObject==0xFFFFFFF0?0x46000000000000C0:0x719B3800AA000C81,NumPut(idObject==0xFFFFFFF0?0x0000000000020400:0x11CF3C3D618736E0,IID,"Int64"),"Int64"), "Ptr*", pacc)=0
 Return ComObjEnwrap(9,pacc,1)
}

Video walking through Excel cell alignment with AutoHotkey

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.