Select a DataGrid Row by its Number

June 12, 2010

This is the kind of thing that’s too easy to forget (or lose track of):

To select a row in a grid by its number:

Dim WScript, i, NumberOfRow

If Not Datagrid1.Focused Then DataGrid1.SetFocus
Set WScript = Application.CreateObject("WScript.Shell")

For i=0 To NumberOfRow-1
     WScript.SendKeys "{DOWN}"

Set WScript = Nothing

GridName.Selection.Item(i) contains the value of the DataGrid’s Key Field for the selected row.

If you want to access a selected node, you should use GridName.SelectedNodes.Item(i) .

If you want to get the value for any field in a selected row, then use GridName.GetFieldValue(GridName.Selection.Item(i), FieldName).

On the topic of SendKeys, there’s also this:

Dim objSh

Set objSh = CreateObject("WScript.Shell")

' Example sending TAB key
objSh.SendKeys "{TAB}", False

' Example sending ALT+F5
objSh.SendKeys "%{F5}", False

' etc

Set objSh = Nothing