0
votes

Developing a planning tool in Word, I use a table for each session of a training course. I want to format individual cells according to their column (two color options for each). For layout purposes, some title row cells are merged. I want my user to right-click on cells below the "P"-title, then select the activity type which is then color-coded as cell background shading.

Image: Training session table, cells under P only color-coded, no text

Hence my Range object returns runtime error 5992 like "As table has different number of columns, this collection does not offer access to individual columns"

Sub Makro2()
  Dim minCelle As Range
  Selection.SelectCell
  Set minCelle = Selection.Range
  minCelle.Text = minCelle.Columns.First.Index
  ' Here the error occurs. As a starting point, I want VBA to insert col#
End Sub

Once I have established column numbers, I can work on with conditional coloring.

I work in Word 2016, but would like, if possible some backward compatibility. I tried it out on a MWE: a Word 2016 .docm document containing a two-row, three-col table with two cells merged in the first row, and containing a macro with the code above.

1
I'm a bit confused: Do you need to format individual cells (your explanation gives me that impression) or entire columns? In a quick test, the following returns the right column for me, even if cells are merged in the first row: Selection.Cells(1).ColumnIndex - Cindy Meister
Can't check right now, but I will in the morning. Thanks. - Morten Engelsmann

1 Answers

0
votes

Implementing the correction from @CindyMeister below, I get the actual column number.

Sub Makro2()
  Dim minCelle As Range
  Selection.SelectCell
  Set minCelle = Selection.Range
  minCelle.Text = Selection.Cells(1).ColumnIndex
End Sub