vb中是的文本框输入数字自动以千为分隔加逗号

前端之家收集整理的这篇文章主要介绍了vb中是的文本框输入数字自动以千为分隔加逗号前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

添加个输入框text1,然后复制下面代码即可。


Private Sub Text1_Change()
    setFormat Text1
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
    If Not ((KeyAscii > 48 And KeyAscii < 57) Or KeyAscii = 8 Or KeyAscii = 46 Or ((KeyAscii = 43 Or KeyAscii = 45) And Text1.SelStart = 0)) Then KeyAscii = 0
End Sub
Private Sub setFormat(objTxt As TextBox)
    Dim v,strNew$,s1$,intSelStart%
    Dim reg As Object
    Set reg = CreateObject("vbscript.regExp")
    reg.Global = True
    If objTxt.Text = "" Then Exit Sub
    v = Split(objTxt.Text,".")
    s1 = v(0)
    v(0) = Replace(v(0),","")
    reg.Pattern = "(\d{3})"
    v(0) = StrReverse(reg.Replace(StrReverse(v(0)),"$1,")) '每隔3数字加逗号
    reg.Pattern = "^([^\d]*?),"
    v(0) = reg.Replace(v(0),"$1")
    intSelStart = objTxt.SelStart
    objTxt.Text = Join(v,".")
    objTxt.SelStart = intSelStart + Len(v(0)) - Len(s1)
End Sub

猜你在找的VB相关文章