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

猜你喜欢

转载自blog.csdn.net/sysdzw/article/details/51958085