Select row vba word

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Row.Select method (Word)

vbawd10.chm156303359

vbawd10.chm156303359

word

Word.Row.Select

f3c31e32-b316-abf2-fec6-b76e8950b1b5

06/08/2017

medium

Row.Select method (Word)

Selects the specified table row.

Syntax

expression.Select

expression Required. A variable that represents a ‘Row’ object.

Remarks

After using this method, use the Selection object to work with the selected row. For more information, see Working with the Selection Object.

Example

This example selects row one in table one of Report.doc.

Documents("Report.doc").Tables(1).Rows(1).Select

See also

Row Object

[!includeSupport and feedback]

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Ask Question

Asked
11 years, 3 months ago

Modified
2 years, 9 months ago

Viewed
16k times

6

How can I determine the current row where a selection is active of the table in a Word VBA macro?

I’ve tried all variants with no success:

MsgBox Selection.Range
MsgBox Selection.Rows.Item.Index

  • vba
  • ms-word
  • row

Improve this question

edited Jul 5, 2020 at 12:10

Martijn Pieters's user avatar

Martijn Pieters

1.0m288 gold badges4004 silver badges3309 bronze badges

asked Dec 29, 2011 at 13:11

Crimix's user avatar

CrimixCrimix

3991 gold badge2 silver badges11 bronze badges

0

Add a comment
 | 

1 Answer

Sorted by:

Reset to default

15

I figured it out myself:

MsgBox Selection.Information(wdEndOfRangeRowNumber)
MsgBox Selection.Cells(1).RowIndex

Improve this answer

edited Jan 1, 2012 at 20:45

joran's user avatar

joran

168k32 gold badges428 silver badges464 bronze badges

answered Jan 1, 2012 at 20:20

Crimix's user avatar

CrimixCrimix

3991 gold badge2 silver badges11 bronze badges

1

  • And also Selection.Information(wdStartOfRangeRowNumber)

    – Winand

    Oct 27, 2022 at 7:12

Add a comment
 | 

Your Answer

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged

  • vba
  • ms-word
  • row

or ask your own question.

  • The Overflow Blog
  • Are meetings making you less productive?

  • The philosopher who believes in Web Assembly

  • Featured on Meta
  • Improving the copy in the close modal and post notices — 2023 edition

  • Temporary policy: ChatGPT is banned

  • The [protection] tag is being burninated

  • Content Discovery initiative 4/13 update: Related questions using a Machine…

Related

2611

How do you display code snippets in MS Word preserving format and syntax highlighting?

20

VBA How to get path to The Current Users Application data folder?

497

How do I add indexes to MySQL tables?

0

Qualify Selection Object in VBA Word

0

VBA — Macro to extend selection to end of current table column, then find and replace only within that selection

0

VBA Word trying to shade SELECTED cells in one table in word that are bold

0

VBA Macros Lost After Updating to 2010 Word

1

How to make Microsoft Word visible after opening an Excel file in Word VBA

5

Set table column widths in Word macro VBA

Hot Network Questions

  • The Dating Game / Secretary Problem

  • Change size of dingbat

  • Draw a rectangle with partly invisible edges, only corners

  • How did Luke get back to Echo Base after crashing?

  • Why does my company keep putting me under the same manager?

  • Why are 3/4 size guitars not more common?

  • Can you combine two different metrics on different scales by Z-scoring?

  • How does copyrights work for mobile/web applications?

  • Etiquette (and common sense) rules for MTB cyclists

  • Not able to create a mesh from data in obj format using python api

  • What does Thoreau mean about the Tract Society printing the story of Putnam?

  • Horror novel involving teenagers killed at a beach party for their part in another’s (accidental) death

  • Arrow placement issue in syntactic tree using tikz-qtree

  • What’s up with banks closing down their high yield savings accounts and incentives lately?

  • What kind of fallacy is it to say if abolition of something isn’t possible, we shouldn’t attempt to address it at all?

  • How can one transform a neutral lookup table texture for color blindness?

  • The challenge Large Language Models (LLMs) pose to programming-based homework

  • What should I do after my PhD supervisor calls me a retard to my face?

  • Birth time of files are missing if file is created in a logical volume with size less than 512 MB

  • Can I develop Windows, macOS, and Linux software or a game on one Linux distribution?

  • Why are the back of the wings of some aerobatic planes swept forward?

  • Deal or No Deal, Puzzling Edition

  • touch command not able to create file in write-permitted directory

  • Help with understanding this «quote»

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

  1. 09-12-2012, 07:06 AM


    #1

    Solved: Select Multiple Rows in Table?

    Guys, how do I select multiple rows in a table using VBA?

    I can select one row using ActiveDocument.Tables(1).Rows(1).Select

    This will select the first row of the first table; what I need is to select the first three rows of the first table, but am struggling!

    I need to run this on 650 documents, so not using VBA isn’t an option!!

    TIA


  2. 09-12-2012, 01:35 PM


    #2

    Try something like this…
    [VBA]

    Sub Demo()
    Dim rngFirstThreeRows As Range

    With ActiveDocument.Tables(1)
    Set rngFirstThreeRows = .Rows(1).Range
    rngFirstThreeRows.End = .Rows(3).Range.End
    End With
    rngFirstThreeRows.Select
    End Sub
    [/VBA]
    HOWEVER — you probably don’t need to select these rows at all in order to do what you actually want to do. You can get a little more help if you give some specifics.

    But your final code will run significantly faster on 650 documents if you don’t select anything.

    _______________________________________________
    Please don’t cross-post without providing links to your cross-posts. We answer questions for free. Please don’t waste the time of the people helping you.
    For cross-posting etiquette, please read: http://www.excelguru.ca/content.php?184

    — Frosty


  3. 09-12-2012, 01:43 PM


    #3

    Thanks — haven’t tried it yet as the files are at work. Not very good at this stuff at all, so have been using MultiMacro to do the hard work and just selecting my saved macros one at a time to do what I need, and it’s been doing quite well!

    What needs to be done now is to change the first three rows of the first table in each document from dotted horizontal lines to solid lines, but I can’t see how you can do this without selecting them? You can’t select rows etc in a table while recording a macro, so impossible for me to do it that way.


  4. 09-12-2012, 02:03 PM


    #4

    Sorry, I don’t know what MultiMacro is, so I don’t know what hard work it is helping you do… but…

    You can select rows while recording a macro— you just have to use the keyboard to do it (i.e., hold down the shift key, then use some combination of arrow keys/home key/end key/ctrl key, etc etc).

    That will give you the basics of how to apply borders to *something* — from there, you can usually translate the recorded macro (which does use the selection) to something which does not use the selection (and is thus, faster).


  5. 09-12-2012, 02:08 PM


    #5

    Thanks, I never knew you could do that with the keyboard, I’ll give it a try.

    MultiMacro; you save your macros; list them by name in an open word document and leave it open. Run the MultiMacro addin, and it lets you select a folder then applies the listed macros to all documents in the folder……


  6. 09-13-2012, 01:51 PM


    #6

    MultiMacro…essentially the DIR function…


Содержание

  • 1 Adding a Column to a Table
  • 2 Adding a Row to a Table
  • 3 Converting a Table or Rows to Text
  • 4 Converts the current selection to a five-column table, separating the information at commas.
  • 5 Declare the variable tempTable and then select the first table in the document named Log.doc and assign its Range object to tempTable
  • 6 Deletes the first cell in the first row of the first table in the active document and shifts the other cells in the first row to the left to fill the gap:
  • 7 delete the column in which the range testRange ends if the range is more than one column wide:
  • 8 Deleting a Column from a Table
  • 9 Deleting a Row from a Table
  • 10 Deleting Cells
  • 11 Entering Text in a Cell
  • 12 Finding Out Where the Selection Is in the Table
  • 13 Inserting a Cell
  • 14 inserts a new, blank, non-autofitting table containing 10 rows and 5 columns at the current position of the insertion point in the active document:
  • 15 Making Sure the Selection Is within a Table
  • 16 Returning the Text within a Cell
  • 17 Selecting a Column
  • 18 Selecting a Range of Cells
  • 19 Selecting a Row
  • 20 Selecting a Table in the active document:
  • 21 Selects the first table in the current selection:
  • 22 Set the Height property of the row or rows in question by specifying the height in points
  • 23 Setting the Height of One or More Rows
  • 24 Setting the Width of a Column
  • 25 Strip off the last two characters when assigning the Text property to a string:
  • 26 The SetWidth method sets the width of one or more columns and specify how the other columns in the table should change as a result: expression.SetWidth ColumnWidth, RulerStyle
  • 27 The Width property lets you change the width of a column without worrying about the effect on the other columns. Specify the width you want in points-for example:
  • 28 Use the ConvertToText method with a Table object, a Row object, or a Rows collection: converts only the first row of the selected table to tab-delimited text
  • 29 wdDeleteCellsEntireRow deletes the whole row.
  • 30 wdDeleteCellsShiftLeft moves cells across to the left to fill the gap.
  • 31 wdDeleteCellsShiftUp moves cells up to fill the gap.
  • 32 wdEndOfRangeColumnNumber returns the number of the column in which the end of the selection or range falls.

Adding a Column to a Table

   <source lang="vb">

«The following statements use the Count property to check the number of columns in the first table in the active document and
Sub add()

   With ActiveDocument.Tables(1)
       .Select
       If .Columns.Count < 5 Then
           Do Until .Columns.Count = 5
               .Columns.add BeforeColumn:=.Columns(.Columns.Count)
           Loop
       End If
   End With

End Sub

</source>
   
  

Adding a Row to a Table

   <source lang="vb">

Sub addRow()

   Documents("yourDoc.doc").Tables(1).Rows.Add BeforeRow:=1

End Sub

</source>
   
  

Converting a Table or Rows to Text

   <source lang="vb">

Sub sep()

   Selection.Tables(1).ConvertToText Separator:="*"

End Sub

</source>
   
  

Converts the current selection to a five-column table, separating the information at commas.

   <source lang="vb">

Sub sele()

   Set myTable = Selection.ConvertToTable(wdSeparateByCommas, _
       Selection.Paragraphs.Count, 5, , , , , , , , , , , True, _
       wdAutoFitContent, wdWord9TableBehavior)

End Sub

</source>
   
  

Declare the variable tempTable and then select the first table in the document named Log.doc and assign its Range object to tempTable

   <source lang="vb">

Sub tableSel()

   Dim tempTable
   Documents("Log.doc").Tables(1).Select
   Set tempTable = Selection.Tables(1).Range
   tempRange.Tables(2).Select

End Sub

</source>
   
  

Deletes the first cell in the first row of the first table in the active document and shifts the other cells in the first row to the left to fill the gap:

   <source lang="vb">

Sub del()

   ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
       ShiftCells:=wdDeleteCellsShiftLeft

End Sub

</source>
   
  

delete the column in which the range testRange ends if the range is more than one column wide:

   <source lang="vb">


    With testRange
        If .Information(wdStartOfRangeColumnNumber) <> _
            .Information(wdEndOfRangeColumnNumber) Then _
            .Tables(1).Columns(.Information _
            (wdEndOfRangeColumnNumber)).Delete
    End With
</source>
   
  

Deleting a Column from a Table

   <source lang="vb">

Sub del()

   ActiveDocument.Tables(1).Columns(1).Delete

End Sub

</source>
   
  

Deleting a Row from a Table

   <source lang="vb">

Sub del()

   Documents("yourDoc.doc").Tables(3).Rows(1).Delete

End Sub

</source>
   
  

Deleting Cells

   <source lang="vb">

«wdDeleteCellsEntireColumn deletes the whole column the specified cell or cells is in.
Sub del()

   ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
       ShiftCells:=wdDeleteCellsEntireColumn

End Sub

</source>
   
  

Entering Text in a Cell

   <source lang="vb">

Sub text()

   With Selection.Tables(1).Rows(1)
       .Cells(1).Range.text = "Sample text in first cell."
       .Cells(2).Range.text = "Sample text in second cell."
       .Cells(3).Range.text = "Sample text in third cell."
   End With

End Sub

</source>
   
  

Finding Out Where the Selection Is in the Table

   <source lang="vb">

Sub sel()

   If Selection.Information(wdAtEndOfRowMarker) = True Then _
       Selection.MoveLeft Unit:=wdCharacter, Count:=1

End Sub

</source>
   
  

Inserting a Cell

   <source lang="vb">

Sub insert()

   Documents("Tables.doc").Tables(1).Rows(1).Cells.Add _
       BeforeCell:=Documents("Tables.doc").Tables(1).Rows(1).Cells(2)

End Sub

</source>
   
  

inserts a new, blank, non-autofitting table containing 10 rows and 5 columns at the current position of the insertion point in the active document:

   <source lang="vb">

Sub table()

   ActiveDocument.Tables.add Range:=Selection.Range, NumRows:=10, _
       NumColumns:=5, DefaultTableBehavior:=wdWord8TableBehavior

End Sub

</source>
   
  

Making Sure the Selection Is within a Table

   <source lang="vb">

Sub withTable()

   If Selection.Information(wdWithInTable) = True Then
       "take actions here
   End If

End Sub

</source>
   
  

Returning the Text within a Cell

   <source lang="vb">

Sub text()

   Dim strCellText As String
   strCellText = ActiveDocument.Tables(1).Rows(2).Cells(1).Range.Text
   Debug.Print strCellText

End Sub

</source>
   
  

Selecting a Column

   <source lang="vb">

«To select a column, use the Select method with the appropriate Column object.
Sub sel()

   Documents("yourDoc.doc").Tables(3).Columns(2).Select

End Sub

</source>
   
  

Selecting a Range of Cells

   <source lang="vb">

«To select a range of cells within a table, declare a Range variable, assign to it the cells you want to select, and then select the range
Sub cellSel()

   Dim myCells As Range
   With ActiveDocument
       Set myCells = .Range(Start:=.Tables(1).Cell(1, 1).Range.Start, _
           End:=.Tables(1).Cell(1, 4).Range.End)
       myCells.Select
   End With

End Sub

</source>
   
  

Selecting a Row

   <source lang="vb">

Sub sel()

   Documents("Tables.doc").Tables(.Tables.Count).Rows.Last.Select

End Sub

</source>
   
  

Selecting a Table in the active document:

   <source lang="vb">

Sub table1()

   ActiveDocument.Tables(1).Select

End Sub

</source>
   
  

Selects the first table in the current selection:

   <source lang="vb">

Sub tableSel1()

   Selection.Tables(1).Select

End Sub

</source>
   
  

Set the Height property of the row or rows in question by specifying the height in points

   <source lang="vb">

Sub height()

   Documents("Tables.doc").Tables(3).Rows(3).Height = 33

End Sub

</source>
   
  

Setting the Height of One or More Rows

   <source lang="vb">

Sub rowHeight()

   ActiveDocument.Tables(4).Rows(2).HeightRule = wdRowHeightAuto

End Sub

</source>
   
  

Setting the Width of a Column

   <source lang="vb">

Sub auto()

   ActiveDocument.Tables(1).Columns.AutoFit

End Sub

</source>
   
  

Strip off the last two characters when assigning the Text property to a string:

   <source lang="vb">

Sub strip()

   Dim strCellText As String
   
   strCellText = ActiveDocument.Tables(3).Rows(2).Cells(1).Range.Text
   Debug.Print strCellText
   strCellText = Left(strCellText, Len(strCellText) - 2)
   Debug.Print strCellText

End Sub

</source>
   
  

The SetWidth method sets the width of one or more columns and specify how the other columns in the table should change as a result: expression.SetWidth ColumnWidth, RulerStyle

   <source lang="vb">

Sub ruler()

   ActiveDocument.Tables(1).Columns(2).SetWidth ColumnWidth:=50, _
       RulerStyle:=wdAdjustProportional

End Sub

</source>
   
  

The Width property lets you change the width of a column without worrying about the effect on the other columns. Specify the width you want in points-for example:

   <source lang="vb">

Sub width()

   ActiveDocument.Tables(11).Columns(44).Width = 100

End Sub

</source>
   
  

Use the ConvertToText method with a Table object, a Row object, or a Rows collection: converts only the first row of the selected table to tab-delimited text

   <source lang="vb">

Sub tab()

   Selection.Tables(1).Rows(1).ConvertToText Separator:=wdSeparateByTabs

End Sub

</source>
   
  

wdDeleteCellsEntireRow deletes the whole row.

   <source lang="vb">

Sub del()

   ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
       ShiftCells:=wdDeleteCellsEntireRow

End Sub

</source>
   
  

wdDeleteCellsShiftLeft moves cells across to the left to fill the gap.

   <source lang="vb">

Sub del()

   ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
       ShiftCells:=wdDeleteCellsShiftLeft

End Sub

</source>
   
  

wdDeleteCellsShiftUp moves cells up to fill the gap.

   <source lang="vb">

Sub del()

   ActiveDocument.Tables(1).Rows(1).Cells(1).Delete _
       ShiftCells:=wdDeleteCellsShiftUp

End Sub

</source>
   
  

wdEndOfRangeColumnNumber returns the number of the column in which the end of the selection or range falls.

   <source lang="vb">


    With testRange
        If .Information(wdStartOfRangeColumnNumber) <> _
            .Information(wdEndOfRangeColumnNumber) Then _
            .Tables(1).Columns(.Information _
            (wdEndOfRangeColumnNumber)).Delete
    End With
</source>

Old

01-28-2012, 12:39 PM

Jennifer Murphy's Avatar

Competent Performer

How to select the first row of the current table

 

Join Date: Aug 2011

Location: Silicon Valley

Posts: 234

Jennifer Murphy is on a distinguished road

Default

How to select the first row of the current table


I am trying to write a macro to change some table settings. It’s sorta working, but I could use a little help.

1. I can’t figure out how to select the first row of the current table so I can set the font and flag it as a header row.

As I understand it, this code selects the second row in the first table of a document:

Code:

ActiveDocument.Tables(1).Rows(2).Select

Can I then use this code to select the first row in the table where the cursor is?

Code:

Selection.Tables(1).Rows(1).Select

I am also using this code to ensure that the cursor is actually in a table.

Code:

If Selection.Information(wdWithInTable) <> True Then
  MsgBox "The cursor is not in a table", , "MyTableSettings macro"
  Exit Sub
End If

Reply With Quote

Old

01-28-2012, 03:41 PM

Jennifer Murphy's Avatar

Competent Performer

How to select the first row of the current table

 

Join Date: Aug 2011

Location: Silicon Valley

Posts: 234

Jennifer Murphy is on a distinguished road

Default


I think I got it. Here’s the macro. It changes three settings:

  • It turns off the Break Across Pages setting (for rows).
  • It turns off the Auto Fit setting (for columns).
  • It set row 1 as a header row if the user says «Yes».

Here’s the code. Comments appreciated.

Code:

'===========================================================================
'                        My Table Settings
' Correct the table settings to what Word should have made them.
' 07/23/10  Recorded and modified.
' 01/28/12  Add code for header row
'===========================================================================
Sub MyTableSettings()
Const MyName = "MyTableSettings"
Dim SettingBreakOld                 'Old setting
Dim SettingAutoFitOld               'Old setting
Dim SettingHeaderRow As Boolean     'True = set first row as header
Dim SettingHeaderRowOld As Boolean  'Old setting
Dim Msg
'Abort if the cursor is not in a table
If Selection.Information(wdWithInTable) <> True Then
  MsgBox "The cursor is not in a table", vbOKOnly, MyName
  Exit Sub
End If
 
'Ask if they want a header row?
Select Case MsgBox("Set row 1 as header?", vbYesNoCancel, MyName)
  Case vbYes
    SettingHeaderRow = True
  Case vbNo
    SettingHeaderRow = False
  Case vbCancel
    MsgBox "Aborted", vbOKOnly, MyName
    Exit Sub
End Select
'Save old settings
SettingBreakOld = Selection.Rows.AllowBreakAcrossPages
If SettingBreakOld = -1 Then   '-1 = On, 0 = Off
  SettingBreakOld = "On"
ElseIf SettingBreakOld = 0 Then
  SettingBreakOld = "Off"
End If
SettingAutoFitOld = Selection.Tables(1).AllowAutoFit
If SettingAutoFitOld = "True" Then   'True = On, False = Off
  SettingAutoFitOld = "On"
ElseIf SettingAutoFitOld = "False" Then
  SettingAutoFitOld = "Off"
End If
SettingHeaderRowOld = Selection.Tables(1).Rows(1).HeadingFormat
'Set the new ones
Selection.Tables(1).Select                                    'Select the entire table
Selection.Rows.AllowBreakAcrossPages = False                  'Stop rows from breaking
Selection.Tables(1).AllowAutoFit = False                      'Stop auto-resizing
Selection.Tables(1).Rows(1).HeadingFormat = SettingHeaderRow  'Set the heading setting
'Report the results
Msg = "Autofit = Off (was " & SettingAutoFitOld & "), " & vbCrLf & _
      "Break = Off (was " & SettingBreakOld & "), " & vbCrLf & _
      "Header row = " & SettingHeaderRow & " (was " & SettingHeaderRowOld & ")"
MsgBox Msg, vbOKOnly, MyName
End Sub

Reply With Quote

Old

01-28-2012, 07:03 PM

Default


Hi Jennifer,

Your code could be simplified a bit. In particular, there’s no need to select the whole table before working on it. Aside from executing faster, not selecting it has the advantage of leaving the selected range unchanged:

Code:

Sub MyTableSettings()
Const MyName = "MyTableSettings"
Dim SettingBreakOld                 'Old setting
Dim SettingAutoFitOld               'Old setting
Dim SettingHeaderRowOld As Boolean  'Old setting
Dim Msg
'Abort if the cursor is not in a table
If Selection.Information(wdWithInTable) = False Then
  MsgBox "The cursor is not in a table", vbOKOnly, MyName
  Exit Sub
End If
'Save old settings
With Selection.Tables(1)
  SettingBreakOld = (.Rows.AllowBreakAcrossPages = True)
  SettingAutoFitOld = (.AllowAutoFit = True)
  SettingHeaderRowOld = (.Rows(1).HeadingFormat = True)
  'Set the new ones
  .Rows.AllowBreakAcrossPages = False                  'Stop rows from breaking
  .AllowAutoFit = False
  'Ask if they want a header row?
  Select Case MsgBox("Set row 1 as header?", vbYesNoCancel, MyName)
    Case vbYes
      .Rows(1).HeadingFormat = True
    Case vbNo
      .Rows(1).HeadingFormat = False
    Case vbCancel
      MsgBox "Aborted", vbOKOnly, MyName
      Exit Sub
  End Select
  'Report the results
  Msg = "Autofit = True (was " & SettingAutoFitOld & "), " & vbCrLf & _
      "Break = True (was " & SettingBreakOld & "), " & vbCrLf & _
      "Header row = " & (.Rows(1).HeadingFormat = True) & " (was " & SettingHeaderRowOld & ")"
  MsgBox Msg, vbOKOnly, MyName
End With
End Sub

__________________
Cheers,
Paul Edstein
[Fmr MS MVP — Word]

Reply With Quote

Old

01-28-2012, 08:12 PM

Jennifer Murphy's Avatar

Competent Performer

How to select the first row of the current table

 

Join Date: Aug 2011

Location: Silicon Valley

Posts: 234

Jennifer Murphy is on a distinguished road

Default


Paul,

Thanks for the suggestions.

The reason I selected the whole table was because I wanted the «Do not break» option to be applied to all rows. From your code, it appears that the

Code:

With Selection.Tables(1)
 
   ...
 
End With

acts as if the table were selected within that With block. Is that correct? This is indeed much better code.

The other change that I noticed is you changed my test from «<> True» to «= False». Is there a reason for that? I wrote it my way in case there is some other possibility besides True and False, such as Null or Empty. I have been burned before, especially with VBA, when the application (Word) returns odd results. I want to do something if it’s true only.

Reply With Quote

Old

01-28-2012, 08:24 PM

Default


Hi Jennifer,

In a sense the ‘With Selection.Tables(1) .. End With’ block does act as if the table were selected. Since your selection point is already within the table, that’s all that’s needed.

Quote:

The other change that I noticed is you changed my test from «<> True» to «= False». Is there a reason for that?

Only that your SettingHeaderRowOld variable returns True/False, whilst the others were returning On/Off — which amounted to the same thing. AllowAutoFit can only be True/False, though .Rows.AllowBreakAcrossPages (and, hence SettingBreakOld) could be True/False/Undefined — the latter if some rows were allowed to break and others weren’t.

__________________
Cheers,
Paul Edstein
[Fmr MS MVP — Word]

Reply With Quote

Old

01-29-2012, 11:41 AM

Jennifer Murphy's Avatar

Competent Performer

How to select the first row of the current table

 

Join Date: Aug 2011

Location: Silicon Valley

Posts: 234

Jennifer Murphy is on a distinguished road

Default


I am making progress, but have run into a couple of puzzling results.

I wanted to use this same syntax to change the font and the borders. I started by capturing the code using the recorder. This is what I got:

Code:

Sub Macro1()
  Selection.Font.Name = "Calibri"
  Selection.Borders(wdBorderTop).LineStyle = wdLineStyleNone
  Selection.Borders(wdBorderLeft).LineStyle = wdLineStyleNone
  Selection.Borders(wdBorderBottom).LineStyle = wdLineStyleNone
  Selection.Borders(wdBorderRight).LineStyle = wdLineStyleNone
  Selection.Borders(wdBorderVertical).LineStyle = wdLineStyleNone
  Selection.Borders(wdBorderDiagonalDown).LineStyle = wdLineStyleNone
  Selection.Borders(wdBorderDiagonalUp).LineStyle = wdLineStyleNone
End Sub

Then I tried to adapt it to my macro.

For the font change line, I got a Compile error: «Methor or data member not found».

For the last two lines of the border settings, I got a Runtime error ‘5941’: «The requested member of the collection does not exist».

These lines are shown in red and commented out.

Code:

With Selection.Tables(1)
  .Rows.AllowBreakAcrossPages = False
  .AllowAutoFit = False
  .Rows(1).HeadingFormat = SettingHeaderRow
'  .Font.Name = "Calibri"
  If SettingHeaderBorderOff Then  'Turn all but bottom border off
    With Selection.Tables(1).Rows(1)
      .Borders(wdBorderTop).LineStyle = wdLineStyleNone
      .Borders(wdBorderLeft).LineStyle = wdLineStyleNone
      .Borders(wdBorderRight).LineStyle = wdLineStyleNone
      .Borders(wdBorderVertical).LineStyle = wdLineStyleNone
'      .Borders(wdBorderDiagonalDown).LineStyle = wdLineStyleNone
'      .Borders(wdBorderDiagonalUp).LineStyle = wdLineStyleNone
    End With
  End If
End With

What am I doing wrong?

Reply With Quote

Old

01-29-2012, 03:35 PM

Default


Hi Jennifer,

For the font, you need to use:
.Range.Font.Name = «Calibri»

For the borders, I deleted the reference to ‘Selection.Tables(1)’. I don’t get any errors with:

Code:

  If SettingHeaderBorderOff Then  'Turn all but bottom border off
    With .Rows(1)
      .Borders(wdBorderTop).LineStyle = wdLineStyleNone
      .Borders(wdBorderLeft).LineStyle = wdLineStyleNone
      .Borders(wdBorderRight).LineStyle = wdLineStyleNone
      .Borders(wdBorderVertical).LineStyle = wdLineStyleNone
      .Borders(wdBorderDiagonalDown).LineStyle = wdLineStyleNone
      .Borders(wdBorderDiagonalUp).LineStyle = wdLineStyleNone
    End With
  End If

I did have to comment out the ‘If’ test, as there doesn’t seem to be a SettingHeaderBorderOff variable setting to test in the code you’ve supplied.

__________________
Cheers,
Paul Edstein
[Fmr MS MVP — Word]

Reply With Quote

Old

01-29-2012, 05:40 PM

Jennifer Murphy's Avatar

Competent Performer

How to select the first row of the current table

 

Join Date: Aug 2011

Location: Silicon Valley

Posts: 234

Jennifer Murphy is on a distinguished road

Default


OK. I changed the font code to use the «.range». That now works. Is there some way I should have known that or been able to figure it out?

I deleted the ‘Selection.Tables(1)’, but I still get the error.

I’ve posted the entire macro below. It has the right variables declared. I made a bunch of changes to the way the options are selected and reported, but the core code is the same.

Code:

Sub MyTableSettings()
 
Const MyName = "MyTableSettings"
Dim SettingBreakOld, SettingAutoFitOld, SettingFontSw, SettingFontOld, _
    SettingHdrRowSw, SettingHdrRowOld, SettingHdrBrdrOffSw, SettingSelectTableSw _
    As Boolean  'Setting variables
Dim Msg, MsgAutoFit, MsgBreak, MsgHdrRow, MsgFont, MsgBorder As String
 
'Abort if the cursor is not in a table
If Selection.Information(wdWithInTable) <> True Then
  MsgBox "The cursor is not in a table", vbOKOnly, MyName
  Exit Sub
End If
 
'Get user options
If vbYes = MsgBox("Take all defaults?", vbYesNo, MyName) Then
  SettingHdrRowSw = True
  SettingHdrBrdrOffSw = True
  SettingFontSw = True
  SettingSelectTableSw = True
Else
  SettingHdrRowSw = (vbYes = MsgBox("Set row 1 as header?", vbYesNo, MyName))
  SettingHdrBrdrOffSw = (vbYes = MsgBox("Header row borders off?", vbYesNo, MyName))
  SettingFontSw = (vbYes = MsgBox("Set font to Calibri?", vbYesNo, MyName))
  SettingSelectTableSw = (vbYes = MsgBox("Leave table selected?", vbYesNo, MyName))
End If
 
With Selection.Tables(1)
 
  'Save the old settings
  SettingBreakOld = .Rows.AllowBreakAcrossPages
  SettingAutoFitOld = .AllowAutoFit
  SettingHdrRowOld = .Rows(1).HeadingFormat
  SettingFontOld = .Range.Font.Name
 
  'Set the rest of the new settings
  .Rows.AllowBreakAcrossPages = False                 'Do not allow rows to break across pages
    MsgBreak = "Break = " & .Rows.AllowBreakAcrossPages & " (was " & SettingBreakOld & ")" & vbCrLf
  .AllowAutoFit = False                               'Do not autofit columns
    MsgAutoFit = "Autofit = " & .AllowAutoFit & " (was " & SettingAutoFitOld & ")" & vbCrLf
  .Rows(1).HeadingFormat = SettingHdrRowSw            'Set header row on/off
    MsgHdrRow = "Header row = " & .Rows(1).HeadingFormat & " (was " & SettingHdrRowOld & ")" & vbCrLf
 
  If SettingFontSw Then         'Set font?
    .Range.Font.Name = "Calibri"
    MsgFont = "Font = " & .Range.Font.Name & " (was " & SettingFontOld & ")" & vbCrLf
  Else
    MsgFont = ""
  End If
 
  If SettingHdrBrdrOffSw Then  'If no header row borders, turn all but bottom off
    With .Rows(1)
      .Borders(wdBorderTop).LineStyle = wdLineStyleNone
      .Borders(wdBorderLeft).LineStyle = wdLineStyleNone
      .Borders(wdBorderRight).LineStyle = wdLineStyleNone
      .Borders(wdBorderVertical).LineStyle = wdLineStyleNone
'      .Borders(wdBorderDiagonalDown).LineStyle = wdLineStyleNone
'      .Borders(wdBorderDiagonalUp).LineStyle = wdLineStyleNone
    End With
    MsgBorder = "Header row borders off"
  Else
    MsgBorder = "Header row borders unchanged"
  End If
 
  If SettingSelectTableSw Then Selection.Tables(1).Select 'Leave table selected?
 
  'Report the results
  Msg = MsgAutoFit & MsgBreak & MsgHdrRow & MsgFont & MsgBorder
  MsgBox Msg, vbOKOnly, MyName
 
End With
End Sub

Reply With Quote

Old

01-29-2012, 06:15 PM

Default


Hi Jennifer,

The code runs just fine for me, on both Word 2003 & 2010. Maybe there’s a problem with your document or your Word 2007 installation. Repairing Word (Word Options|Resources|Diagnose) may help.

I note that you’ve declared your variables thus:

Code:

Dim SettingBreakOld, SettingAutoFitOld, SettingFontSw, SettingFontOld, _
    SettingHdrRowSw, SettingHdrRowOld, SettingHdrBrdrOffSw, SettingSelectTableSw _
    As Boolean  'Setting variables
Dim Msg, MsgAutoFit, MsgBreak, MsgHdrRow, MsgFont, MsgBorder As String

You should be aware that this means that all except SettingSelectTableSw and MsgBorder are Variants.

I also note that, with the borders for example, you have an option to delete them or leave them alone. IMHO it would be better to allow the user to choose to have or not have the borders, including on a table that presently lacks them. In that case, you’d need something like:

Code:

  Dim Bdr As Long
  If SettingHdrBrdrOffSw Then  'If no header row borders, turn all but bottom off
    Bdr = 0
    MsgBorder = "Header row borders off"
  Else
    Bdr = 1
    MsgBorder = "Header row borders on"
  End If
  With .Rows(1)
    .Borders(wdBorderTop).LineStyle = Bdr
    .Borders(wdBorderLeft).LineStyle = Bdr
    .Borders(wdBorderRight).LineStyle = Bdr
    .Borders(wdBorderVertical).LineStyle = Bdr
    .Borders(wdBorderDiagonalDown).LineStyle = Bdr
    .Borders(wdBorderDiagonalUp).LineStyle = Bdr
  End With

BTW, you could reduce:
If SettingSelectTableSw Then Selection.Tables(1).Select ‘Leave table selected?
to:
If SettingSelectTableSw Then .Select ‘Leave table selected?

__________________
Cheers,
Paul Edstein
[Fmr MS MVP — Word]

Reply With Quote

Old

01-29-2012, 06:50 PM

Jennifer Murphy's Avatar

Competent Performer

How to select the first row of the current table

 

Join Date: Aug 2011

Location: Silicon Valley

Posts: 234

Jennifer Murphy is on a distinguished road

Default


Dang. You are right about the Dim statement. I looked on the MSFT website:

http://msdn.microsoft.com/en-us/library/7ee5a7s1(v=vs.80).aspx

and found this paragraph.

Different Types. You can specify different data types for different variables by using a separate As clause for each variable you declare. Alternatively, you can declare several variables to be of the same type by using a common As clause. Each variable takes the data type specified in the first As clause encountered after its variablename part.

It sure seems to me to say that I can group them as I did. They even give this example:

Code:

Dim a, b, c As Single, x, y As Double, i As Integer
' a, b, and c are all Single; x and y are both Double

I guess it works in VB but not in VBA. Another cute little gotcha from MSFT.

I ran the diagnostics. It found no errors. I don’t need those 2 lines, so I’ll just delete them.

As for the borders, I would do as you suggest it I were writing this for general use. It’s just for me and mainly for one project where I need the tables to look a certain way. I don’t need every option.

Anyway, thanks for all your help.

Reply With Quote

INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

How do I select the first 2 rows of a table in word

How do I select the first 2 rows of a table in word

(OP)

25 Jun 09 04:13

Hey there,

this is a pretty simple question — I just need help because when I run the macro recorder I can’t select stuff with the mouse, I need to select the first 2 rows in a table in Word so I can set them as header rows: eg.

 ‘Set the first two rows as repeatable heading rows
 ‘ This ain’t workin’….
    Selection.Tables(1).Range(Start:=Selection.Tables(1).Rows(1), End:=Selection.Tables(1).Rows(2)).Select
…..
    Selection.Rows.HeadingFormat = True

I just need to know how to do selections or define ranges in word VBA and I just can’t get it right at the moment

Thanks,
Lea

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Понравилась статья? Поделить с друзьями:
  • Select range in excel macro
  • Select one row in excel vba
  • Select one cell in excel vba
  • Select number vba word
  • Select line in word