Tag Archives: TextBox

VBA – TextBox Date Mask (updated)

Máscara de data (e uma pequena homenagem)

A long time ago, I published a hint which coming from the forum that explains how to set a TextBox to have a mask, like date, phone, etc in the link bellow:

https://www.tomasvasquez.com.br/blog/microsoft-office/vba-fomatar-textbox-data-telefone-cpf-nos-eventos-keypress-e-change

The code works well, but it has a bug for date mask. The bug don’t allow ther user to erase all text using the backspace or delete key. Well, after some effort, here is a way to fix it:

Private KeyCodeToAvoid As MSForms.ReturnInteger
 
Private Sub TextBoxData_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Set KeyCodeToAvoid = KeyCode
End Sub
 
Private Sub TextBoxData_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    'Limita a Qde de caracteres
    TextBoxData.MaxLength = 10
 
    'para permitir que apenas números sejam digitados
    If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
        KeyAscii = 0
    End If
 
End Sub
 
Private Sub TextBoxData_Change()
'Formata : dd/mm/aaaa
'não avalia se for backspace ou delete
    If Not (KeyCodeToAvoid = KeyCodeConstants.vbKeyBack Or KeyCodeToAvoid = KeyCodeConstants.vbKeyDelete) Then
        If Len(TextBoxData) = 2 Or Len(TextBoxData) = 5 Then
            TextBoxData.Text = TextBoxData.Text & "/"
            SendKeys "{End}", True
        End If
    End If
    'zera o keycode
    KeyCodeToAvoid = KeyCodeConstants.vbKey0
End Sub

I hope you enjoy it!

VBA – Fomatar TextBox (Data, Telefone, CPF) nos Eventos KeyPress e Change

Publicado por Mauro Coutinho

Exemplos de mascara

Colegas, conforme solicitação em outro Forum, referente a alguns tipos de formatação em TextBox, segue as rotinas utilizando-se os Eventos KeyPress e Change :

Formata DATA : Supondo que o TextBox esteja com o nome “txtData”, a formatação ocorrerá quando da digitação :

Private Sub txtData_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
	'Limita a Qde de caracteres
	txtData.MaxLength = 8
 
	'para permitir que apenas números sejam digitados
	If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
		KeyAscii = 0
	End If
 
End Sub
 
Private Sub txtData_Change()
	'Formata : dd/mm/aa
	If Len(txtData) = 2 Or Len(txtData) = 5 Then
		txtData.Text = txtData.Text & "/"
		SendKeys "{End}", True
	End If
End Sub

Formata CPF:

Private Sub Txt_CPF_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
	'Limita a Qde de caracteres
	Txt_CPF.MaxLength = 14
 
	 Select Case KeyAscii
		Case 8, 48 To 57 ' BackSpace e numericos
		  If Len(Txt_CPF) = 3 Or Len(Txt_CPF) = 12 Then
			Txt_CPF.Text = Txt_CPF.Text & "."
			SendKeys "{End}", False
 
		ElseIf Len(Txt_CPF) = 7 Then
			Txt_CPF.Text = Txt_CPF.Text & "."
 
		ElseIf Len(Txt_CPF) = 11 Then
			Txt_CPF.Text = Txt_CPF.Text & "-"
			SendKeys "{End}", False
		  End If
 
		Case Else ' o resto é travado
			KeyAscii = 0
	  End Select
End Sub

Veja um exemplo utilizando CPF com verificação de Digito :
http://www.planilhando.com.br/forum/viewtopic.php?f=10&t=2780&p=12637&hilit=cpf#p12637

Foramata Numeros de Fones : TextBox Fone para dois numeros formato : 2222-3344 / 3333-4567 :

Private Sub txtFone_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
		'Limita a Qde de caracteres
		txtFone.MaxLength = 21     
 
		 Select Case KeyAscii
		Case 8, 48 To 57 ' BackSpace e numericos
		  If Len(txtFone) = 4 Or Len(txtFone) = 10 Then
			txtFone.Text = txtFone.Text & "-"
			SendKeys "{End}", False
 
		ElseIf Len(txtFone) = 9 Then
			txtFone.Text = txtFone.Text & " / "
 
		ElseIf Len(txtFone) = 16 Then 'Or Len(txtFone) = 20 Then
			txtFone.Text = txtFone.Text & "-"
			SendKeys "{End}", False
		  End If
 
		Case Else ' o resto é travado
			KeyAscii = 0
	  End Select
 
End Sub

Formato Horas, com validação se a Hora é valida, não tenho a fonte, ja faz um tempo que usei esta rotina :

Private Sub txtHoras_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
	Dim TimeStr As String
 
	Set TextLength = txtHoras
 
	On Error GoTo EndMacro
	With txtHoras
		If HasFormula = False Then
 
		Select Case Len(TextLength)
 
			Case 1
				TimeStr = "00:0" &amp; TextLength
			Case 2
				TimeStr = "00:" &amp; TextLength
			Case 3
				TimeStr = Left(TextLength, 1) & ":" & Right(TextLength, 2)
			Case 4
				TimeStr = Left(TextLength, 2) & ":" & Right(TextLength, 2)
 
			'Case 5 ' ex: 12345 = 01:23:45
			'        TimeStr = Left(TextLength, 1) & ":" & Mid(TextLength, 2, 2) & ":" & Right(TextLength, 2)
			'Case 6 ' ex: 123456 = 12:34:56
			'        TimeStr = Left(TextLength, 2) & ":" & Mid(TextLength, 3, 2) & ":" & Right(TextLength, 2)
 
			Case Else
			  MsgBox "HORA EM BRANCo !!!"
					  'With TextBox1
					  '    .SetFocus
						  '.SelStart = 0
						  '.SelLength = Len(.Text)
					'  End With
			  Exit Sub
 
		End Select
			Application.EnableEvents = False
			Formula = TimeValue(TimeStr)
			txtHoras = TimeStr
			sCancel = False
		End If
	End With
 
	GoTo Fim
 
EndMacro:
 
	MsgBox "HORA Inválida !!!"
		  With txtHoras
		   .SetFocus
		   .SelStart = 0
		   .SelLength = Len(.Text)
	  End With
	  sCancel = True
 
Fim:
	Application.EnableEvents = True
End Sub
 
Private Sub txtHoras_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'Limita a Qde de caracteres
	txtHoras.MaxLength = 4
 
	Select Case KeyAscii
			Case 8, 48 To 57 ' BackSpace e numericos
			  'If Len(txtHoras) = 2 Or Len(txtHoras) = 6 Then
			  '  txtHoras.Text = txtHoras.Text & ":"
				SendKeys "{End}", False
			 ' End If
			Case Else ' o resto é travado
				KeyAscii = 0
		  End Select
End Sub

Formata Textbox somente com um numero de Telefone e (dd), Formato (xx) xxxx-xxxx:

Private Sub txtFone_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
	'Limita a Qde de caracteres
	txtFone.MaxLength = 14
 
	'Formato (xx) xxxx-xxxx
	If Len(txtFone) = 0 Then
		txtFone.Text = "("
	End If
 
	If Len(txtFone) = 3 Then
		txtFone.Text = txtFone & ") "
	End If
 
	If Len(txtFone) = 9 Then
		txtFone.Text = txtFone & "-"
	End If
 
End Sub

Textbox com dois numeros de Telefone e (dd), Formato (xx) xxxx-xxxx / xxxx-xxxx:

Private Sub txt2Fone_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
		'Limita a Qde de caracteres
		txt2Fone.MaxLength = 26
 
		'Formato (xx) xxxx-xxxx / xxxx-xxxx
		If Len(txt2Fone) = 0 Then
			txt2Fone.Text = "("
		End If
 
		If Len(txt2Fone) = 3 Then
			txt2Fone.Text = txt2Fone & ") "
		End If
 
		Select Case KeyAscii
 
			 Case 8, 48 To 57 ' BackSpace e numericos
			   If Len(txt2Fone) = 9 Or Len(txt2Fone) = 10 Then
				 txt2Fone.Text = txt2Fone.Text & "-"
				 SendKeys "{End}", False
 
			 ElseIf Len(txt2Fone) = 14 Then
				 txt2Fone.Text = txt2Fone.Text & " / "
 
			 ElseIf Len(txt2Fone) = 21 Then
				 txt2Fone.Text = txt2Fone.Text & "-"
				 SendKeys "{End}", False
			   End If
 
			 Case Else ' o resto é travado
			KeyAscii = 0
 
	  End Select
 
End Sub

Façam os testes, só não esqueçam de arrumarem os nomos dos controles Textbox conforme estão nas rotinas.

Quem tiver mais algumas rotinas interessantes e quiser postar fiquem a vontade.

Link para o tópico do Fórum:

http://tomasvasquez.com.br/forum/viewtopic.php?f=17&t=1505&p=7213#p7213

Javascript – Campo texto permitindo somente digitação de números

Uma necessidade bem comum em sistemas comerciais voltados para web é a validação/consistência de valores inseridos em campos ou controles. Porém, como sabemos, os controles HTML e seu contexto são bem, digamos, “traiçoeiros”.

Não temos neles toda a riqueza de uma interface gráfica ou um controle efetivo de seus eventos. Mas como o Javascript tem se tornado cada vez mais indispensável na construção desses sistemas, mesmo não tendo que sê-lo, nada como apelar para ele em casos como esse.

A função disponibilizada abaixo garante por meio do onkeydown evento Javascript que somente valores numéricos sejam digitados em um campo texto.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* função para permitir a digitação de números decimais e inteiros
*/
function ForceNumericInput(event, This, AllowDecimal, AllowMinus)
{
if(arguments.length == 1)
{
var s = This.value;
// garante que o sinal de "-" seja o primeiro do índice
var i = s.lastIndexOf("-");
if(i == -1)
return;
if(i != 0)
This.value = s.substring(0,i)+s.substring(i+1);
return;
}
switch(event.keyCode)
{
case 8:     // backspace
case 9:     // tab
case 37:    // left arrow
case 39:    // right arrow
case 46:    // delete
event.returnValue = true;
return;
}
if(event.keyCode == 189)     // sinal de número de negativo
{
if(AllowMinus == false)
{
CancelEventExecution(event);
return;
}
// aguarda até que o controle tenha sido atualizado
var s = "ForceNumericInput(document.getElementById('"+This.id+"'))";
setTimeout(s, 250);
return;
}
if(AllowDecimal &amp;&amp; event.keyCode == 188)
{
if(This.value.indexOf(",") &gt;= 0)
{
// restringe a digitação de apenas uma vírgula
CancelEventExecution(event);
return;
}
event.returnValue = true;
return;
}
// permite caracteres entre 0 e 9
if(event.keyCode &gt;= 48 &amp;&amp; event.keyCode &lt;= 57)
{
event.returnValue = true;
return;
}
CancelEventExecution(event);
}
/*
* Cancela a execução de uma function mapeada por um evento
*/
function CancelEventExecution(event)
{
if (navigator.appName == "Netscape")
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
}

Para aplicar a função em um controle input, as opções seriam as seguintes:

Para permitir a digitação de números inteiros de decimais positivos ou negativos

1
2
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric" value=""
    onkeydown="ForceNumericInput(event, this, true, true)" />

Para permitir a digitação de inteiros positivos ou negativos

1
2
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, false, true)" />

Para permitir a digitação de inteiros e decimais positivos

1
2
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, true, false)" />

Para permitir a digitação de somente inteiros positivos

1
2
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, false, false)" />

A função acima tem como base um exemplo postado no site CodeProject (http://www.codeproject.com/KB/scripting/JavaScriptForceNumInput.aspx), porém, com a limitação de funcionar apenas no Internet Explorer.

Foram aplicadas algumas correções como a permissão de navegar por meio da tecla TAB, o que não estava previsto na função original. A função CancelEventExecution foi criada para garantir o cancelamento da execução do evento em navegadores não Internet Explorer. também foi necessário adicionar o parâmetro event, que é implícito no nvagedor da Microsoft, mas precisa ser informada nos demais.

Com isso, a função passar a funcionar corretamente na maior parte dos navegadores.

Aplicando ao função no ASP.NET

Abaixo segue um pequeno exemplo de como aplicar esta função a um controle TextBox no ASP.NET:

1
2
3
TextBox.Attributes.Add("onkeydown", string.Format(
"ForceNumericInput(event, this, {0}, {1});",
true.ToString().ToLower(), true.ToString().ToLower()));

Abraços

Tomás