获取Dvatagrid第r行c列的内容可以用下面代码获得
DataGrid1.Col = r
DataGrid1.Row = c
msgbox DataGrid1.Text
但如果datagrid1中有滚动条,要得到滚动下面某行某列的内容时,系统会提示说:行号无效!
这是由于DataGrid1.Row只能在[1,datagrid.visiblerows]间取值。当行号大于visiblerows(默认18)时,系统就会报错。这种情况一般使用DATAGRID绑定的记录集来移动当前记录指针实现。下面给出一种利用DATAGRID滚动条事件的方法解决这个问题:
Private Sub Command1_Click()
Dim r As Integer, temp As String, gettext As String
Randomize
r = Int(Rnd * DataGrid1.ApproxCount + 1) '任意行
torc DataGrid1, r, 1 '第一行第一列
temp = InputBox("DATAGRID 目前随机定位在第" & r & "行第1列,你想现在移动到第几行,第几列?", "提示", Int(Rnd * DataGrid1.ApproxCount + 1) & "," & Int(Rnd * DataGrid1.Columns.Count + 1))
'随机输入行列
torc DataGrid1, Split(temp, ",")(0), Split(temp, ",")(1), gettext
MsgBox "第" & Split(temp, ",")(0) & "行第" & Split(temp, ",")(1) & "列的值为" & gettext '选定该行该列并取其值
End Sub
Sub torc(ByVal dgrid As DataGrid, ByVal r As Integer, ByVal c As Integer, Optional ByRef gettext As String) '选定DGRID第r行c列单元格
If r < dgrid.VisibleRows Then
dgrid.Row = r - 1
Else
dgrid.Scroll 0, r - dgrid.FirstRow '从FirstRow行下滚r-FirstRow行
dgrid.Row = 0 '选第一个可见行
End If
If c < dgrid.VisibleCols Then
dgrid.Col = c - 1
Else
dgrid.Scroll c - DataGrid1.LeftCol, 0 '从当前列下左滚c - DataGrid1.LeftCol列
dgrid.Col = 0 '选第一个可见行
End If
gettext = dgrid.Text '取值
End Sub
Private Sub Form_Load() '填充一个datagrid
Dim adoRecordset As New ADODB.Recordset
Dim i As Integer, j As Integer, num As Integer
For i = 0 To 5 '为Recordset六个字段,即为 DataGrid 添加六列
adoRecordset.Fields.Append "n * " & i + 1, adVariant, , adFldMayBeNull + adFldIsNullable + adFldUpdatable
Next i
Randomize
num = Int(Rnd * 100 + 1)
With adoRecordset
.Open
For j = 1 To num
.AddNew
.Fields(0) = j
.Fields(1) = 2 * j
.Fields(2) = 3 * j
.Fields(3) = 4 * j
.Fields(4) = 5 * j
.Fields(5) = 6 * j '加num条记录,即为 DataGrid 添加num行
Next j
.MoveFirst
End With
Set DataGrid1.DataSource = adoRecordset '绑定 DataGrid 的数据源
End Sub