I have written a small function to expedite naming cells:
Public Sub InputSelectedNames()
For Each Cell In Selection
On Error Resume Next
Dim strName As String
strName = InputBox("Enter name for cell " & Cell.Address(False, False) & ":", "Name cell")
If Len(strName) = 0 Then
Exit Sub
End If
ActiveSheet.Names.Add Name:=strName, RefersTo:=Cell
Next Cell
End Sub
This works great until I try to enter a unicode string as a name. If I enter something like "αβγ" it appears as "aß?" in the InputBox.
I've read about VBA using ANSI encoding so I understand why this is the case. The example solution given in that tutorial works for displaying unicode (by passing a pointer instead of a string object), but I wasn't able to utilize the same idea for an InputBox.
If I enter these characters through Excel's 'Define Name' button on the formula tab, or through referencing the character in another cell it works fine, so the mistranslation definitely seems to lay in the InputBox.
My guess is that I'll have to make a Userform to handle the input, unless anyone knows a way to get InputBox to play nicely with unicode?
Creating a custom InputBox did solve this problem.
frmInputBox : UserForm
lblOutput : Label providing prompt
txtInput : TextBox for input
cmdOK : CommandButton for accepting input
cmdCancel : CommandButton for aborting prompt
VBA Form Code:
Private Sub cmdOK_Click()
Accept
End Sub
Private Sub cmdCancel_Click()
Cancel
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Cancel
End Sub
Private Sub txtInput_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
Accept
ElseIf KeyCode = vbKeyEscape Then
Cancel
End If
End Sub
Private Sub Accept()
Me.Hide
End Sub
Private Sub Cancel()
txtInput.Text = ""
Me.Hide
End Sub
Public Function Prompt(strPrompt As String, Optional strTitle As String = "Input", Optional strDefault As String = "")
With Me
.Caption = strTitle
.lblOutput.Caption = strPrompt
.txtInput.Text = strDefault
.StartUpPosition = 0
.Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
.Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
.Show
End With
If txtInput.Text <> "" Then
Prompt = txtInput.Text
Else
Prompt = ""
End If
Unload Me
End Function
Called like:
strMyName = frmInputBox.Prompt("What's your name?", "Name Prompt")
Related
I'm trying to get both addition and subtraction options to work and display the proper symbol between each label box. I've been running into an error, which VBA highlights for me. The boxes A, B, and C need to be valued at 10, 11, and 12. When you click a box it's supposed to populate the first empty box with the value. When both boxes are full and you click another letter, its should not be changed, instead the values will be locked until you hit clear.
Current code:
Private Sub Addition_Click()
Me.Result = (Me.LblFirstNum + 0) + (Me.LblSecondNum + 0)
'lblresult = Val(LblFirstNum) + Val(LblSecondNum)
End Sub
Private Sub BtnA_Click()
With LblFirstNum
'to display text
.Caption = "10"
.TextAlign = fmTextAlignCenter
'wrap text
.WordWrap = True
.Font.Size = 18
End With
End Sub
Private Sub BtnB_Click()
With LblSecondNum
'to display text
.Caption = "11"
.TextAlign = fmTextAlignCenter
'wrap text
.WordWrap = True
.Font.Size = 18
End With
End Sub
Private Sub BtnC_Click()
With LblSecondNum
'to display text
.Caption = "12"
.TextAlign = fmTextAlignCenter
'wrap text
.WordWrap = True
.Font.Size = 18
End With
End Sub
Private Sub Calculate_Click()
'Me.Result = (Me.LblFirstNum + 0) + (Me.LblSecondNum + 0)
lblresult.Value = Val(LblFirstNum.Value) + Val(LblSecondNum.Value)
End Sub
Private Sub Clear_Click()
Unload UserForm1
UserForm1.Show
End Sub
Private Sub CommandButton2_Click()
'Exit Command
UserForm1.Hide
End Sub
Private Sub Result_Change()
End Sub
Private Sub Label4_Click()
End Sub
Private Sub LblFirstNum_Click()
End Sub
Private Sub LblSecondNum_Click()
End Sub
Private Sub LblSign_Click()
End Sub
Private Sub Subtraction_Click()
'Me.Result = (Me.LblFirstNum + 0) - (Me.LblSecondNum + 0)
lblresult.Value = Val(LblFirstNum.Value) - Val(LblSecondNum.Value)
End Sub
In Calculate_Click() and Subtraction_Click(), you've tried to retrieve the text shown on a label using LblFirstNum.Value and LblSecondNum.Value. Labels don't have a "Value" property. The correct property to use is "Caption".
In Addition_Click(), it's unclear whether Result is the correct name for the control you're trying to reference. Elsewhere in this code, you have lblresult so you should establish which is the correct name and use that throughout.
You may also want to check the use of Unload in Clear_Click() (assuming that UserForm1 is the form we are working with). Your current code will probably result in an automation error on the UserForm1.Show line
' I'm looking to create placeholder text (ghosting text) to help users know what to type in the field, but I want it to act very similar to on-line forms where the placeholder text does not disappear upon entering a textbox, but only disappears if you type new text into it.
' enterfieldbehavior is set to 1 - fmEnterFieldBehaviorRecallSelection in properties to avoid selecting placeholder text
Private Sub userform_initialize()
TextBox2.Value = "Name" 'upon starting UserForm, the placeholder text is launched in the textbox
TextBox2.ForeColor = &H8000000C 'grey
End Sub
Private Sub TextBox2_Enter()
If TextBox2.Text <> "Name" Then
TextBox2.SelStart = TextBox2.SelLength 'Upon entering the textbox, the cursor is placed only at the start and not the middle or end of the placeholder text
Else
' I need the oppositie of the above, to put the cursor at the end of text as the placeholder text is gone
End If
End Sub
Private Sub TextBox2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
TextBox2.SelStart = TextBox2.SelLength ' If a user uses the mouse to enter the textbox
End Sub
Private Sub TextBox2_Change()
If TextBox2.Text <> "Name" Then
TextBox2.Text = ""
TextBox2.ForeColor = &H8000000C 'grey
Else
TextBox2.Value = TextBox2.Value ' This is where I'm lost as I want to earse the holder text, and let the user type whatever they want
TextBox2.ForeColor = vbBlack
End If
End Sub
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox2.Text = "" Then
TextBox2.Text = "Name" ' If there are no changes to the textbox, replace the placeholder text
TextBox2.ForeColor = &H8000000C 'grey
Else
End If
End Sub
Here is how I would do it:
Private Sub Label1_Click()
TextBox1.SetFocus
End Sub
Private Sub TextBox1_Change()
Label1.Visible = Len(TextBox1.Text) = 0
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Label1.Visible = Len(TextBox1.Text) = 0
End Sub
Private Sub UserForm_Initialize()
With Label1
.SpecialEffect = fmSpecialEffectSunken
.BackColor = vbGrayText
.Caption = " Name"
End With
End Sub
The easiest solution in only 1 line of code is:
Duplicate (copy/paste) your TextBox2 and name it e.g. TextBox2PlaceHolder
Set its Text property to whatever placeholder value you want, eg. "YYYY/MM/DD"
Set its Enabled property to False so that text color will be light gray
Send it to the background just behind your original TextBox2 (same Left and Top properties)
And finally, the masterpiece of code below will just switch the TextBox2.BackStyle to transparent if no text exists and so will let the placeholder appear!
Private Sub TextBox2_Change()
TextBox2.BackStyle = IIf(Len(TextBox2.Text) = 0, fmBackStyleTransparent, fmBackStyleOpaque)
End Sub
Here's what that looks like:
My code has a listbox filled with common small strings of text that the user can click to add to a texbox instead of manually typing them out.
It works in everyway except the previously selected item cannot be clicked again to add to textbox.
I've tried setting listbox.selected = -1 and listbox1.value ="" and when I do this the text is added twice and not unselected.
At one point I was able to make a button that just does listbox1.value = "" and it worked, but when I add it after my code it fails and does the double text thing.
Private Sub ListBox1_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.selected(i) Then
selecteditemtext = ListBox1.List(i)
End If
Next i
TextBox2.Text = TextBox2.Text & selecteditemtext & ", "
What I need it for the selected listbox item become unselected after being clicked so it can be clicked again if needed.
When I run this code line by line it works. but all together it adds the text twice.
Private Sub ListBox1_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.selected(i) Then
selecteditemtext = ListBox1.List(i)
End If
Next i
TextBox2.Text = TextBox2.Text & selecteditemtext & ", "
call listdeselect
end sub
sub listdeselect()
sheet1.listbox1.value = ""
end sub
I believe I have your solution :)
Control the deselection in the MouseUp event as shown below:
Private Sub ListBox1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
ListBox1.ListIndex = -1
End Sub
As long as you don't interrupt the MouseUp event (such as with a MsgBox), this seems to work fine.
Sample code I have used is below:
Private Sub UserForm_Activate()
ListBox1.AddItem "asd"
ListBox1.AddItem "sad"
ListBox1.AddItem "dsa"
ListBox1.AddItem "das"
End Sub
Private Sub ListBox1_Click()
Sheets(1).Cells(1).Value = ListBox1.List(ListBox1.ListIndex)
'MsgBox "hi" 'notice this disrupts the MouseUp event...
End Sub
Private Sub ListBox1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
ListBox1.ListIndex = -1
End Sub
I hope this resolves your issue,
Cheers
I am trying to highlight entered value in TextBox. TextBox value is representing date value in date forma DD-MM-YYYY. I wrote some code to validate if inserted date is ok (in example 31 of April).
Hightlight itself is not a problem, however I want to do this right after an error occurs. So when I insert 31-04-2014, I should get the message "You have inserted wrong date" and the date value should hightlighted. For now it shows me message, highlights value and focus is set to another CommandButton
So far I made something like this:
Private Sub data_faktury_AfterUpdate()
Dim dzien As Byte, miesiac As Byte
Dim rok As Integer
On Error GoTo blad:
dzien = Mid(data_faktury.Value, 1, 2)
miesiac = Mid(data_faktury.Value, 4, 2)
rok = Right(data_faktury.Value, 4)
Call spr_date(dzien, miesiac, rok)
Exit Sub
blad:
If Err.Number = 13 Then
If data_faktury <> "" Then
If Len(data_faktury) < 10 Then: MsgBox ("Źle wpisana data faktury.")
End If
End If
End Sub
And code for 2nd procedure:
Sub zle()
MsgBox ("Wybrałeś zły dzień")
With Faktura.data_faktury
.SetFocus
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
This is a bit long for a comment so here goes. The basic principle is to use the exit event and cancel when necessary. To prevent this being fired when you close the form, you need to use a flag variable - example userform code:
Private bSkipEvents As Boolean
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If bSkipEvents Then Exit Sub
With TextBox1
If Not IsValidDate(.Text) Then
Cancel = True
MsgBox "Invalid date"
.SelStart = 0
.SelLength = Len(.Text)
End If
End With
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
bSkipEvents = True
End Sub
I have a listbox in a userform in Excel 2007.
Some cells in my worksheet contain more than 10 rows (data with ALT ENTER).
I'm trying to clean and display the data. I don't want to change the column width to 1000, but I'd like to use a mouseover box to show all the cell data.
Is there another idea that would work?
With mouse over would be possible to do it but it is complicated I think. Here I have another simpler idea: on double click in list box a multi line text box with selected list item(s) data will be shown. This text box has the same position and size as the list box. On the user form click text box hides. Here is some sample code, to test it you need form with list box named "ListBox1":
Option Explicit
Public ListItemInfo As Control
Private Sub UserForm_Initialize()
Set ListItemInfo = Me.Controls.Add("Forms.TextBox.1", "ListItemInfo", False)
With Me.ListItemInfo
.Top = Me.ListBox1.Top
.Left = Me.ListBox1.Left
.Width = Me.ListBox1.Width
.Height = Me.ListBox1.Height
.MultiLine = True
End With
End Sub
Private Sub ListBox1_Change()
Me.ListItemInfo.text = GetSelectedItemsText
End Sub
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
SwitchListItemInfo
End Sub
Private Sub UserForm_Click()
SwitchListItemInfo
End Sub
Private Function GetSelectedItemsText() As String
Dim text As String
Dim i As Integer
For i = 0 To Me.ListBox1.ListCount - 1
If Me.ListBox1.Selected(i) Then
text = text & Me.ListBox1.List(i) & vbNewLine
End If
Next i
GetSelectedItemsText = text
End Function
Private Sub SwitchListItemInfo()
If Me.ListItemInfo.text = "" Then Exit Sub
Me.ListItemInfo.Visible = Not Me.ListItemInfo.Visible
Me.ListBox1.Visible = Not Me.ListBox1.Visible
End Sub