Share via

Need comparable MS-Word code for Excel's Range.Offset property

Anonymous
2019-01-10T22:14:45+00:00

I would greatly appreciate any help in converting the following Excel VBA code to Word VBA code:

Sub Test()

    Dim i As Integer

    Dim rng As Range

    Set rng = ActiveSheet.Range("A1")  ' In Word, I assume this line would be Set rng = ActiveDocument.Range(0, 0)

    For i = 1 To 10

        rng.Value = "xxx"  ' In Word, I assume this line would be rng.Text = "xxx" 

        rng.Offset(0, 1).Value = "yyy"

        Set rng = rng.Offset(1, 0)

    Next i

End Sub

Thanks in advance for any assistance.

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Jay Freedman 207.7K Reputation points Volunteer Moderator
2019-01-10T22:59:54+00:00

The only way this makes sense in Word is if you're dealing with a table; there is no equivalent for plain text.

In Word, you would address the cells directly rather than by Offset, by using the Table.Cell(row,column) property. Of course, you could do arithmetic on the row and column values if you wanted to.

Sub TestWord()

    Dim tbl As Table

    Dim i As Integer

    Dim rowNum As Integer

    If ActiveDocument.Tables.Count > 0 Then

        Set tbl = ActiveDocument.Tables(1)

        With tbl

            If .Columns.Count < 2 Then .Columns.Add

            For i = 1 To 10

                If .Rows.Count < i Then .Rows.Add

                .Cell(Row:=i, Column:=1).Range.Text = "xxx"

                .Cell(Row:=i, Column:=2).Range.Text = "yyy"

            Next i

        End With

    Else

        MsgBox "No table found in this document.", , "Error"

    End If

End Sub

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

Answer accepted by question author

Doug Robbins - MVP - Office Apps and Services 323.1K Reputation points MVP Volunteer Moderator
2019-01-10T22:57:51+00:00

Use

Dim i As Long

With ActiveDocument

    For i = 1 To 9

        .Range.InsertAfter "xxx" & vbTab & "yyy" & vbCr

    Next i

    .Range.InsertAfter "xxx" & vbTab & "yyy" & vbCr

    .Range.ConvertToTable

End With

If you do not want it in a table, delete the .Range.ConvertToTable command

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Anonymous
    2019-01-10T23:30:22+00:00

    Thanks, Jay, for your solution, too!  I also appreciate the Word VBA education in adding text/data to a table.  Very helpful.

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2019-01-10T23:26:45+00:00

    Thanks, Doug, for your solution.  That did the trick!

    Was this answer helpful?

    0 comments No comments