My ultimate goal is to generate a tool to predict the width of a string, so that I can avoid text overflow when printing reports in MS Access 2010. Options like CanGrow
are not useful, because my reports cannot have unpredicted page breaks. I cannot cut off text.
To this end I discovered the undocumented WizHook.TwipsFromFont
function in Access. It returns the width in twips of a string given font and other characteristics. It has proven quite useful as a starting point. Based on various user generated guides, I developed the following in Access:
Public Function TwipsFromFont(ByVal sCaption As String, ByVal sFontName As String, _
ByVal lSize As Long, Optional ByVal lWeight As Long = 400, _
Optional bItalic As Boolean = False, _
Optional bUnderline As Boolean = False, _
Optional lCch As Long = 0, _
Optional lMaxWidthCch As Long = 0) As Double
'inspired by http://www.team-moeller.de/?Tipps_und_Tricks:Wizhook-Objekt:TwipsFromFont
WizHook.Key = 51488399
Dim ldx As Long
Dim ldy As Long
Call WizHook.TwipsFromFont(sFontName, lSize, lWeight, bItalic, bUnderline, lCch, _
sCaption, lMaxWidthCch, ldx, ldy)
'Debug.Print CDbl(ldx)
TwipsFromFont = CDbl(ldx)
'TwipsFromFont = 99999
End Function
However, the data that will end up in Access is initially going to be generated in Excel 2010. Therefore, I would like to call this function in Excel, so I can check strings as they are created. To this end, I developed the following in Excel:
Public Function TwipsFromFontXLS() As Double
Dim obj As Object
Set obj = CreateObject("Access.Application")
With obj
.OpenCurrentDatabase "C:\MyPath\Jeremy.accdb"
TwipsFromFontXLS = .Run("TwipsFromFont", sCaption = "Hello World!", _
sFontName = "Arial Black", lSize = 20)
.Quit
End With
Set obj = Nothing
End Function
When I run debug.Print TwipsFromFont("Hello World!","Arial Black",20)
in Access I get back 2670. When I run debug.Print TwipsFromFontXLS()
in Excel I get back 585.
In Access, if I set TwipsFomFont = 9999
, then debug.Print TwipsFromFontXLS()
will return 9999
.
Any thoughts on where my disconnect is?
sCaption = "Hello World"!
is wrong, it should just be"Hello World!"
. This makes the long run maintainability a little tougher, but I am now getting the returned values I am expecting. – JarvissCaption = "Hello World!"
What version of Access/Excel are you using? And OS? – PenmanshipsCaption = "Hello World!"
. I am using MS Office 2010 on Windows 7. – Jarvis