How can I replace spaces in a textbox with "_"?
Printable View
How can I replace spaces in a textbox with "_"?
In real time? Otherwise, just use Replace(Text1.Text, " ", "_")
Hello GDOG34,
Merri is right. We hope it was helpful. :)
Realtime...
:wave:vb Code:
'~~~ When the user presses a key, it's ASCII value is checked to find whether it is SPACE or not. If so, replace it with "_"'s ASCII value Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = 32 Then '~~~ 32 is for SPACE character KeyAscii = 95 '~~~ 95 is for underscore character End If End Sub
akhileshbc's solution doesn't prevent pasting text with spaces from the clipboard. For that the hard thing is that text can be pasted using both mouse & keyboard, there is no general event for finding out the user is pasting text, and thus the code becomes a bit lengthy:And it is a bit of a hack at it. The contents of the clipboard are temporarily changed if paste is detected being pressed from the keyboard and each time mouse button is pushed down. Not very clean, but works.Code:Option Explicit
Private m_ClipOld As String
Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyV And Shift = vbCtrlMask Then
If Clipboard.GetFormat(vbCFText) Then
m_ClipOld = Clipboard.GetText
Clipboard.SetText Replace(m_ClipOld, " ", "_")
End If
End If
End Sub
Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyV And Shift = vbCtrlMask Then
If StrPtr(m_ClipOld) <> 0 Then
Clipboard.SetText m_ClipOld
m_ClipOld = vbNullString
End If
End If
End Sub
Private Sub Text1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Clipboard.GetFormat(vbCFText) Then
m_ClipOld = Clipboard.GetText
Clipboard.SetText Replace(m_ClipOld, " ", "_")
End If
End Sub
Private Sub Text1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
If StrPtr(m_ClipOld) <> 0 Then
Clipboard.SetText m_ClipOld
m_ClipOld = vbNullString
End If
End Sub
Above both codes are correct and this would also help u a lot
http://www.vbforums.com/showthread.php?t=636550