View Single Post
 
Old 09-20-2018, 08:45 AM
Kebap Kebap is offline Windows 7 64bit Office 2010 64bit
Novice
 
Join Date: Sep 2018
Posts: 3
Kebap is on a distinguished road
Question Table column width wrong - unless macro paused!?

Hey all!

I am investigating a VBA issue where Word 2016 behaves differently than Word 2010.

However during Investigation I found out, even Word 2010 will behave differently depending if I set a breakpoint in VBA or not.

Sounds weird? It is!

I dumbed down my macro to the following. A table is created with three columns. Text is written to the table. The columns width is adjusted as well. Sounds easy, right?

This width setting does not take effect on 2016 but does on 2010.
When stepping through the macro one command at a time, it will work on 2016 as well.
Only if the original macro is run "at full speed" (also as part of a much larger macro cascade), then the width is ignored.

To simulate that on 2010, I put a content-less loop after the table creation. I also put a MsgBox for your comparison in screenshot. As you can see, when the Messagebox arrives, the width has not been set. Only after clicking "ok" and another pause, then the table will magically readjust its width.

I assume this readjustment for some reason does not happen anymore for VBA 2016. Because it uses the exact same commands.

See screenshot before clicking OK:
https://imgur.com/lJmfNMs

And adjusted with after clicking:
https://imgur.com/OLOeHcn

Following are the VBA commands used for the test. As you can see, the width should be adjusted long before the message box appears..!
Code:
Sub Test()
 
text_a = "A text"
text_b = "A longer text to make the column need more width"
text_c = "More text"
 
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=3, _
  DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=False
With Selection.Tables(1)
  .ApplyStyleHeadingRows = True
  .ApplyStyleLastRow = True
  .ApplyStyleFirstColumn = True
  .ApplyStyleLastColumn = True
  .AllowAutoFit = False
  .PreferredWidthType = wdPreferredWidthPoints
  .PreferredWidth = CentimetersToPoints(17.5)
  .LeftPadding = 0
  .RightPadding = 0
End With
 
Selection.TypeText Text:=text_a
Selection.Cells.PreferredWidth = CentimetersToPoints(3.2)
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:=text_b
Selection.Cells.PreferredWidth = CentimetersToPoints(13.4)
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:=text_c
 
For i = 1 To 100
  DoEvents: DoEvents: DoEvents: DoEvents: DoEvents
Next i
 
For i = 1 To 10000000: Next i
 
MsgBox ("OK")
 
End Sub

What am I doing wrong? How can I fix this to always see the correct width immediately and not run into those problems in VBA 2016?

Can you recommend any other way to create a table of 3 columns with predefined width like this?

Thanks a lot in advance!
Reply With Quote