也可将以下代码写入到datagrid的keypress事件中,并写明在哪列执行下面代码 If KeyAscii = 13 Then SendKeys "{tab}" Else If KeyAscii <> 8 And KeyAscii <> 46 Then If KeyAscii < 48 Or KeyAscii > 57 Then KeyAscii = 48 End If End If End If
在keyascii事件中 if datagrid.col=你想限制的列 then if keyascii<48 or keyascii>57 then if keyascii<>vbkeyback then keyascii=0 '只能输入数字和后退键,其他的没有内容 endif endif
在datagrid的keypress事件中 If nkeyascii <> vbKeyBack And nkeyascii <> vbKeyReturn Then If Not (Chr(nkeyascii) Like "[0-9]") Then nkeyascii = 0 End If End If
假設你是限制DBGrid1的第3列只能輸入數字,原代碼如下: Private Sub DBGrid1_KeyPress(KeyAscii As Integer) If KeyAscii=13 then SendKeys "{Tab}" End If If DBGrid1.Col = 2 Then KeyAscii = onlynum(KeyAscii) End If End Sub Public Function onlynum(kk As Integer) As Integer Dim ss As String ss = "0123456789." If InStr(ss, Chr(kk)) = 0 And kk <> 8 And kk <> 13 Then onlynum = 0 Else onlynum = kk End If End Function
If KeyAscii = 13 Then
SendKeys "{tab}"
Else
If KeyAscii <> 8 And KeyAscii <> 46 Then
If KeyAscii < 48 Or KeyAscii > 57 Then
KeyAscii = 48
End If
End If
End If
if datagrid.col=你想限制的列 then
if keyascii<48 or keyascii>57 then
if keyascii<>vbkeyback then keyascii=0 '只能输入数字和后退键,其他的没有内容
endif
endif
If nkeyascii <> vbKeyBack And nkeyascii <> vbKeyReturn Then
If Not (Chr(nkeyascii) Like "[0-9]") Then
nkeyascii = 0
End If
End If
问一个低级问题:怎样定义该列的数据字段类型 ?
还有疑惑,datagrid初始只有两列,怎样增加?
Rs.addnew
Private Sub DBGrid1_KeyPress(KeyAscii As Integer)
If KeyAscii=13 then
SendKeys "{Tab}"
End If
If DBGrid1.Col = 2 Then
KeyAscii = onlynum(KeyAscii)
End If
End Sub
Public Function onlynum(kk As Integer) As Integer
Dim ss As String
ss = "0123456789."
If InStr(ss, Chr(kk)) = 0 And kk <> 8 And kk <> 13 Then
onlynum = 0
Else
onlynum = kk
End If
End Function