PDA

View Full Version : Cell Selection Macro in Word Help



brentt03
08-25-2017, 09:11 AM
Hello all!

I have a document in which I need to select a cell, add comment, select next cell, add comment, etc

I was wanting to make a macro to automatically do this for me, problem is the tables vary by overall number of rows, and they will never be the same. Is there a way to create a macro to do this for me?

Also if I select row 1, column 1 and add a comment, then i will need to select row 1, column 2 to add a different comment.

This code works, but doesn't give me range

Sub Macro1()
'
' Macro1 Macro
'
'
ActiveDocument.Tables(1).Columns(2).Cells(1).Range.Select
Selection.Comments.Add Range:=Selection.Range
Selection.TypeText Text:="rn"
ActiveDocument.Tables(1).Columns(2).Cells(2).Range.Select
Selection.Comments.Add Range:=Selection.Range
Selection.TypeText Text:="rn"




End Sub

gmayor
08-25-2017, 08:39 PM
The following should get you started


Sub Macro1()
'Define the variables used
Dim oTable As Table
Dim iRow As Integer
Dim oCell As Range
On Error GoTo lbl_Exit
Set oTable = Selection.Tables(1) 'or activedocument.tables(1)
For iRow = 1 To oTable.Rows.Count 'count the table rows and process each in turn
With oTable.Rows(iRow)
Set oCell = .Cells(1).Range 'set a range to the cell in column 1
oCell.End = oCell.End - 1 'remove the cell end character from the range
'or if there is already text in the cell you wish to keep
'oCell.Collapse wdCollapseStart
oCell.Text = "Text for column A cells" 'If there is text you want to keep add e.g. a space or tab character after the text to separate it


Set oCell = .Cells(2).Range 'set a range to the cell in column 2
oCell.End = oCell.End - 1 'remove the cell end character from the range
'or if there is already text in the cell you wish to keep
'oCell.Collapse wdCollapseStart
oCell.Text = "Text for column B cells"
End With
Next iRow
lbl_Exit:
Set oTable = Nothing
Set oCell = Nothing
Exit Sub
End Sub

mana
08-25-2017, 11:15 PM
Option Explicit


Sub test()
Dim c As Cell

For Each c In ActiveDocument.Tables(1).Range.Cells
MsgBox "Row:" & c.RowIndex & ", Column:" & c.ColumnIndex & ", Text:" & c.Range.Text
Next

End Sub

macropod
08-26-2017, 07:07 AM
Cross-posted at: https://www.excelforum.com/word-programming-vba-macros/1198537-cell-selection-macro-in-word-help.html
Please read VBA Express' policy on Cross-Posting in item 3 of the rules: http://www.vbaexpress.com/forum/faq.php?faq=new_faq_item#faq_new_faq_item3