Clear range selected in Excel listbox and delete range name - excel

Suppose I have a listbox in a userform module. When shown, it contains three range names. Let's call them Range1, Range2, and Range3. When the user clicks on one, I want the corresponding range to be cleared and the range name to be deleted.
Thanks to anyone who can advise me on the code to do this.

Sorry I can't comment.But I think this link will help you.
http://www.ozgrid.com/forum/showthread.php?t=83396

I actually deleted the range. Alternatively, you could use Range(.Value).ClearContents to clear only the data or Range(.Value).Clear to clear the data and formatting from the range.
Private Sub ListBox1_Click()
With ListBox1
If Not IsNull(.Value) Then
On Error Resume Next
Range(.Value).Delete
ThisWorkbook.Names(.Value).Delete
On Error GoTo 0
End If
End With
RefreshRangeList
End Sub
Sub RefreshRangeList()
Dim n As Name
ListBox1.Clear
For Each n In ThisWorkbook.Names
ListBox1.AddItem n.Name
Next
End Sub
Private Sub UserForm_Initialize()
RefreshRangeList
End Sub

Related

Excel Userform pass variable to Range

I have a worksheet which I have set to let the user open a userform if it contains the text "[View Data]". My thought was that I can send the current active cell row into a variable and then apply it when retrieving data. This works partially, I can get the active cell row, but I am unable to apply it within the Range. The error occurs in Read_Data:
Run-time error '9': Subscript out of range
I would appreciate some help in getting to a solution
This is what I have for Modules -> Module1:
Public activeCellNow As Integer
This is what I have in Microsoft Excel Objects -> Sheet1:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With Target
If 1 = .Cells.Count Then
activeCellNow = ActiveCell.row
If .Value = "[View Data]" Then Details.Show
End If
End With
End Sub
This is what I have in Forms -> Details
Private Sub UserForm_Activate()
MsgBox (activeCellNow)
Call Read_Data
End Sub
The message box shows the correct row number
Private Sub Read_Data()
txt_manager.Value = Sheets("Sheet1").Range("B" & (activeCellNow)).Value
End Sub
Resolved issue. I tried it on a new project and the syntax I wrote worked fine. Thanks to #Skin and #FunThomas for the tips :)

Getting the Cell Address of Checkbox when ticked

Hy, I am working on Excel VBA which will get me the Cell Address of the Checkbox I tick at the moment. I am able to get the cell address using following code.
Sub test()
Dim ws As Worksheet
Set ws = Sheets("Sheet 1")
Dim chk As CheckBox
For Each chk In ws.CheckBoxes
Debug.Print chk.TopLeftCell.Offset(0, 0).Address
Next chk
End Sub
This code returns the Cell address of all Check-boxes but I only want one cell address of the checkbox I tick. How can I achieve this. Currently I am trying events to achieve this but have no success so far.
Use the next way, please:
Copy the next Sub in a standard module:
Sub GetChkBoxAddress()
MsgBox ActiveSheet.Shapes(Application.Caller).TopLeftCell.Address
End Sub
Copy the next code, too, and run it:
Sub textAssignMacroChkBox()
Dim sh As Worksheet, s As Shape, chkB As CheckBox
Set sh = ActiveSheet
For Each s In sh.Shapes
If TypeName(s.OLEFormat.Object) = "CheckBox" Then
s.OnAction = "GetChkBoxAddress"
End If
Next
End Sub
Try checking and unchecking the check boxes...
If you need to return the cell address only when the check box is checked (not for unchecking) the code can be adapted...
Edited:
In order to retrieve the cell address only for checking, you can use the next adapted Sub:
Sub GetChkBoxAddress()
If ActiveSheet.Shapes(Application.Caller).OLEFormat.Object.Value = 1 Then
MsgBox ActiveSheet.Shapes(Application.Caller).TopLeftCell.Address
End If
End Sub

Using VBA userform to select ranges on multiple sheets - sheet changes back to original activesheet

I have a userform which has multiple RefEdit controls. I need the user to select ranges from multiple sheets and the userform has to be complete before the rest of the code can run.
Issue: The activesheet is "Sheet1" when the userform is initiated. Each time I select a range on "Sheet2" and click into the next RefEdit the visible Excel sheet returns to "Sheet1". I'd like the sheet to remain on "Sheet2", since clicking between the sheets significantly increases the time it takes to select the data.
Because I need the userform to be completed before continuing with my code, using "vbModeless" doesn't appear to work.
I've tried to step through the userform events which appeared to be relevant but none were activated when I entered the RefEdit, selected the data, or left the RefEdit.
Thanks in advance for any help!
Edit: Using some input from the responses and doing some more research I think I've figured out the problem and a work around.
RefEdit events such as Change or Exit (I tried all of them I think) don't appear to trigger when a change occurs in the control. So I couldn't write code to manipulate the activesheet when I changed the control. A workaround found here: http://peltiertech.com/refedit-control-alternative/ uses a textbox and inputbox to simulate a RefEdit control and will actually trigger when changes are made! Code is below. To add other "RefEdit" controls you should repeat the code in the Userform_Initialize event for each control, then add another TextBox1_DropButtonClick and update TextBox1 to the name of the new control. In use when the control updates the workbook jumps to the previous activesheet and then returns the desired activesheet. Not as smooth as I'd like but much better than it was.
Code:
Private Sub CancelButton_Click()
Unload Me
End
End Sub
Private Sub OKButton_Click()
UserForm1.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
End
End Sub
Private Sub UserForm_Initialize()
Me.TextBox1.DropButtonStyle = fmDropButtonStyleReduce
Me.TextBox1.ShowDropButtonWhen = fmShowDropButtonWhenAlways
End Sub
Private Sub TextBox1_DropButtonClick()
Dim ASheet As String ' Active sheet
Me.Hide
'Use input box to allow user to select a range
On Error Resume Next
Me.TextBox1.Value = Application.InputBox("Select the range containing your data", _
"Select Chart Data", Me.TextBox1.Text, Me.Left + 2, _
Me.Top - 86, , , 0)
On Error GoTo 0
'Check if there is a sheet name - if the range selected is on the activesheet the output of the inputbox doesn't have a sheet name.
If InStr(1, Me.TextBox1.Value, "!", vbTextCompare) > 0 Then ' there is a sheet name
ASheet = Replace(Split(Me.TextBox1.Value, "!")(0), "=", "") ' extract sheet name
Else ' there is no sheet name
Me.TextBox1.Value = "=" & ActiveSheet.Name & "!" & Replace(Me.TextBox1.Value, "=", "") ' add active sheet name to inputbox output
ASheet = ActiveSheet.Name
End If
Worksheets(ASheet).Activate ' set the active sheet
Me.Show
End Sub
Have you tried something as simple as:
Sheets("Sheet2").Select
somewhere in the beginning of your form code ?
Since you haven't posted your code, it's hard to provide a good answer.
Hope this helps a little :)
This form module worked for me.
Private Sub CommandButton1_Click() 'Cancel Button
Unload Me
End Sub
Private Sub CommandButton2_Click() 'GO Button
Dim newSheet As Worksheet
abc = Split(RefEdit1.Value, "!")
cbn = abc(0)
Unload Me
Set newSheet = Worksheets(abc(0))
newSheet.Activate
End Sub

How to compare ListBox text with Sheet name in VBA?

I'm trying to do a User Form that allows to insert a number in a ListBox, in case this number matches with one of sheet names, to select this work sheet. In case there is not a match, to give a message box, that the number was not found.
But i have a problem with defining that the ListBox text must be compared with Sheet names.
It looks in a following way:
The code is following:
Private Sub CommandButton1_Click()
Option Explicit
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
'this line i could not manage
If ws.Name Like "Tel*" Then
Sheets("Tabella Riepilogativa").Select
End If
Else: MsgBox "Phone number was not found"
Next
End Sub
Private Sub Label1_Click()
End Sub
Private Sub ListBox1_Click()
End Sub
Can someone help with it, please?
The Option Explicit belongs at the top of the file.
To find a sheet named "Tel{whatever the user entered in a TextBox}":
Private Sub CommandButton1_Click()
Dim ws As Worksheet, wsFound As Worksheet, searchFor As String
searchFor = "TEL" & UCase$(Trim$(TextBox1.Text))
For Each ws In ThisWorkbook.Sheets
If UCase$(ws.Name) = searchFor Then
Set wsFound = ws
Exit For
End If
Next
If wsFound Is Nothing Then
MsgBox "Not Found (I should probably be a label to save the user an unnecessary click)"
Else
wsFound.Select
End If
End Sub

Single callback macro for multiple form controls (ListBoxes to be specific)

I'm trying to store selected values from a listbox (Excel 2010) with multi selection enabled. This is easily done by iterating through the items in the list to see if they are selected. However, upon adding a number of listboxes, i have to create a callback for each:
Sub ListBox1_Changed()
Call DoStuff(Worksheets("Sheet1").ListBoxes(1))
End Sub
Sub ListBox2_Changed()
Call DoStuff(Worksheets("Sheet1").ListBoxes(2))
End Sub
Sub DoStuff(L as ListBox)
'Do stuff here
Sub
Eventually I will end up with a large number of these ListBoxes across multiple worksheets.
Now my question is: Is it possible to reference the specific box that called the macro and assigning this single function for all my listboxes? I'm guessing something like:
Sub ListBox_Changed(ByVal L as Object)
' This will not work btw ^^^^^^^^
' Magic code goes here.
Call DoStuff(L_converted_to_ListBox_Format)
End Sub
Please note, that I'm not using userforms but have just put the listbox directly in the worksheet.
Thanks!
You can use the Application.Caller to determine which ListBox called the Sub, like this
Sub ListBox_Changed()
Dim v As Variant
Dim lb As ListBox
v = Application.Caller
On Error Resume Next
Set lb = Me.ListBoxes(v)
If Err.Number <> 0 Then Exit Sub
On Error GoTo 0
DoStuff lb
End Sub
Sub DoStuff(lb As ListBox)
Debug.Print lb.List(lb.Value)
End Sub

Resources