Lock Select Box Size In Excel - excel

This seems like a simple thing, but I cannot figure it out, or find it online.
If I select 5 cells in a column(say A1:A5), and I would like to move this selection shape(column 1:5) over (to B1:B5); Is there shortcut to do this? Currently I hit the left arrow, and the select box changes size to just B1, and I have to hit shift and select B2:B5. Ideally I would like to discover a hot key that "locks" the shape of the select box.
It has been suggested by colleagues to write a macro, but this is ineffective in many cases. For example what if instead of a column I wanted to do the same thing with a row, or with a different sized shape. It seems likely that excel has this feature built in.

I'm not sure how a macro would be ineffective. I would write procedures similar to what's below, then assign them to hotkeys. Let me know if it works for you.
Option Explicit
Public rowDim As Long
Public colDim As Long
Public putSel as Boolean
Sub togglePutSel()
putSel = Not putSel
End Sub
Sub GetSelShape()
rowDim = Selection.Rows.Count
colDim = Selection.Columns.Count
putSel = True
End Sub
Sub PutSelShape()
Selection.Resize(rowDim, colDim).Select
End Sub
If you want to make it work for whenever you hit the arrow keys, then in your Sheet code, you can use this. You may want to do a quick check that rowDim and colDim aren't 0. The only issue with this is that you'd be stuck with that behavior unless you create a trigger to stop calling PutSelShape. So, I'd suggest one macro (hotkeyed to GetSelShape) to toggle it, and another hotkey for togglePutSel.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If putSel Then
Call PutSelShape
End If
End Sub

Related

Compile - Syntax Error: When toggling select filter with If Statement

it's me again - I'll get to know this language better eventually.
Basically - I have a big table of data that has autofilter on - range "$B$5:$Z$1697"
However, there is an additional filter on the R column that I want to be toggled on or off.
Therefore I need an If statement that says when the additional filter is on, remove, whereas, if the filter is not on at the time you press the button - apply it.
I've played around with this and watched more videos that I care to admit. However, there must be something I'm overlooking or don't understand.
The code works up until the Else line, which returns:
"Compile Error, Syntax Error".
Can anyone explain what's happening?
If Sheets(4).Range("$B$5:$Z$1697").AutoFilter(Field:=17, Criteria1:="=") = True Then
'If there specific filter on column R is on then
Sheets(4).Range("$B$5:$Z$1697").AutoFilter Field:=17
'Turn off that filter.
Else: Sheets(4).Range("$B$5:$Z$1697").AutoFilter(Field:=17, Criteria1:="=")
'Else, if the filter is off, turn it on.
End If
End Sub
EDIT: I have corrected the code, amending this ELSE line to this
Else: Sheets(4).Range("$B$5:$Z$1697").AutoFilter(Field:=17, Criteria1:="=") = True
However, when I run this now it means that it turns the filter On and then Off again with one push of the button. How do I make it so it onl makes on change at a time.
I.e. if the filter is on when the button is pressed it ONLY turns it off.
And vice versa
The easiest way to toggle a filter on/off is to use an ActiveX Toggle button. When the toggle button is clicked (enabled) your filter will be applied, when clicked again (disabled) your filter is removed. Change the name of the toggle button and Criteria1 to meets your needs.
Private Sub ToggleButton1_Click()
'when selected(enabled) the filter for Col "Q" will be enabled
If ToggleButton1.Value = True Then
Sheets(4).Range("$B$5:$Z$1697").AutoFilter Field:=17, Criteria1:="2"
Else
'when selected again(disabled) the filter for Col "Q" will be Disabled
Sheets(4).Range("$B$5:$Z$1697").AutoFilter Field:=17
End If
End Sub
This is NOT a complete answer, but I can't fit all this into a comment...
I've found that continually using compound references to refer to different objects within Excel can really give me headaches. Using intermediate objects doesn't impose any significant performance penalty at all, so I am in the habit of breaking down the compound reference into a series of intermediate objects. Doing this gives me at least two advantages: 1) I can examine the intermediate objects to make sure of the data I think should be there, and 2) I get far fewer syntax errors because each step gets validated.
So, while I can't check if this is correct since I can't access your data, your logic could look like this
Sub Example()
Dim fourthWS As Worksheet
Dim filteredData As Range
Set fourthWS = ThisWorkbook.Sheets(4)
Set filteredData = fourthWS.Range("$B$5:$Z$1697")
Dim dataIsFiltered As Variant
dataIsFiltered = filteredData.AutoFilter(Field:=17, Criteria1:="=")
If dataIsFiltered Then
'--- turn off the filter
filteredData.AutoFilter Field:=17
Else
'--- turn on the filter
filteredData.AutoFilter Field:=17, Criteria1:="="
End If
End Sub

Editing percentage value in Userform TextBox

I am attempting to create a textbox which allows users to input a percentage between 1-5% in my Excel-VBA Userform. I have created the textbox and added code to restrict the formatting to always show as a percentage. My problem is that when I attempt to edit the default percentage in the textbox by pressing backspace the decimal moves two spaces to the right instead of deleting any present values. Below is a copy of my code. Please note that the Textbox is not locked.
Private Sub PV_change()
PV.Text = Format(PV.Value, "Percent")
End Sub
You could do your code in the PV_Exit procedure rather than the _Change procedure, but I still think you're asking for trouble this way :)
Private Sub PV_Exit(ByVal Cancel As MSForms.ReturnBoolean)
PV.Value = Format(PV.Value, "Percent")
End Sub
I agree with the objections made previously, but to show a simple solution without error trapping try this:
Private Sub tbPV_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim dblPV As Double
' don't allow backspace
If KeyCode = Asc(vbBack) Then Exit Sub
' Change string to Double value (without percent sign)
dblPV = CDbl(Replace(Me.tbPV.Text, "%", ""))
' Show the formatted result
Me.tbPV.Text = Format(dblPV, "0.00") & "%"
End Sub
Further Remark Naming a text box 'PV' only doesn' t seem to be state of the art. Adding a prefix - e.g. 'tb' or 'txt'- to all your text boxes gives a hint to to control's original type and could give your code a comprehensible structure.
There are number of naming conventions and divergent opinions, but just to give you an impression have a look at
Hungarian in VBA okay? or search within the Stack Overflow's "naming-conventions" tag.
Best Regards

VBA best practices for modules relative to modeless userforms

I came across this similar issue and read the replies: Modeless form that still pauses code execution
I have been attempting to apply in my own situation the suggestion provided by David Zemens. In my situation, I cannot seem to find an approach that incorporates Mr. Zemen's suggestion without also utilizing a GoTo.
I am wondering if there is a better or more elegant solution.
Here is an outline of what I am doing:
I have a UserForm with a Command Button that begins the code execution that will perform several actions on multiple Excel workbooks. As such, there are a number of blocks of code and the successful completion of one block of code allows for the execution of the subsequent block of code.
At a certain point, depending on the situation, the code might require User input; in other situations, the needed data is obtainable from an Excel. If input is needed from the User, another UserForm is displayed.
The User may need to view several different Excel sheets before entering the input, so the UserForm is modeless. So the code comes to a stop until the User enters the needed input and clicks another Command Button.
It is at this point I am having trouble: how to resume the program flow. Is the only way to 'pick-up where it left-off' is by using a GoTo statement? Or is there some way to organize the modules so there is a single consistent program flow, defined in one spot and not duplicated from the point at which User input might be needed?
Here is my take on the problem . Hope I understood the problem correctly.
Assumptions:
There are two user forms.
UserForm1 with a button to start the processing.
UserForm2 with a button to supply intermediate input.
A sub inside a module to start/ launch UserForm1.
VBA Code (for the sub routine)
Sub LaunchUserForm1()
Dim frm As New UserForm1
'/ Launch the main userform.
frm.Show vbModeless
End Sub
VBA Code (for UserForm1)
Private Sub cmdStart_Click()
Dim i As Long
Dim linc As Long
Dim bCancel As Boolean
Dim frm As UserForm2
'/ Prints 1 to 5 plus the value returned from UserForm2.
For i = 1 To 5
If i = 2 Then
Set frm = New UserForm2
'/ Launch supplementary form.
frm.Show vbModeless
'<< This is just a PoC. If you have large number of inputs, better way will be
' to create another prop such as Waiting(Boolean Type) and then manipulate it as and when User
' supplies valid input. Then validate the same in While loop>>
'/ Wait till we get the value from UserForm2.
'/ Or the User Cancels the Form with out any input.
Do While linc < 1 And (linc < 1 And bCancel = False)
linc = frm.Prop1
bCancel = frm.Cancel
DoEvents
Loop
Set frm = Nothing
End If
Debug.Print i + linc
Next
MsgBox "User Form1's ops finished."
End Sub
VBA Code (for UserForm2)
Dim m_Cancel As Boolean
Dim m_prop1 As Long
Public Property Let Prop1(lVal As Long)
m_prop1 = lVal
End Property
Public Property Get Prop1() As Long
Prop1 = m_prop1
End Property
Public Property Let Cancel(bVal As Boolean)
m_Cancel = bVal
End Property
Public Property Get Cancel() As Boolean
Cancel = m_Cancel
End Property
Private Sub cmdlinc_Click()
'/Set the Property Value to 10
Me.Prop1 = 10
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
'/ Diasble X button
Me.Cancel = True
Me.Hide
Cancel = True
End Sub
OK so here are my thoughts.
You have a userform frmSelectUpdateSheet which you wish to use in order to allow the user to select the sheet, when the sheet can't be determined programmatically. The problem is that if you do .Show vbModeless (which allows the user to navigate the worksheet/s), then code continues to execute which either leads to errors or otherwise undesired output.
I think it's possible to adapt the method I described in the previous answer. However, that's out of the question here unless you're paying me to reverse engineer all of your code :P
Assuming you have a Worksheet object variable (or a string representing the sheet name, etc.) which needs to be assigned at this point (and that this variable is Public in scope), just use the CommandButton on the form to assign this based on the selected item in the frmSelectUpdateSheet list box.
This is probably a superior approach for a number of reasons (not the least of which is trying to avoid application redesign for this sort of fringe case), such as:
This keeps your form vbModal, and does prevent the user from inadvertently tampering with the worksheet during the process, etc.
Using this approach, the thread remains with the vbModal displayed frmSelectUpdateSheet, and you rely on the form's event procedures for control of process flow/code execution.
It should be easier (and hence, cheaper) to implement; whether you're doing it yourself or outsourcing it.
It should be easier (and hence, cheaper) to maintain.
NOW, on closer inspection, it looks like you're already doing this sort of approach with the cmdbtnSelect_Click event handler, which leads me to believe there's a related/follow-up problem:
The sheet names (in listbox) are not sufficient for user to identify the correct worksheet. So if the user needs the ability to "scroll" the sheet (e.g., to review data which does not fit in the window, etc.), then add some spinner buttons or other form controls to allow them to navigate the sheet.

Disable button on a userForm

I'm trying to figure out how to disable a button within my userForm if a certain cell within my spreadsheet equals a certain number. I tried the code stated below, but it isn't working.
Private Sub UserForm_Initialize()
Label2 = Sheets("DATA").Range("AM2").Value
Label4 = Sheets("DATA").Range("AO2").Value
Label7 = Format(Sheets("DATA").Range("R8").Value, "Currency")
If Sheets("DATA").Range("AL10").Value = 10 Then
ActiveSheet.Shapes("CommandButton1").Select
UserFormact_Upgrade.CommandButton1.Enabled = False
Else
End If
End Sub
Your code should be working, as you're on the right path.
To test it, simply create a new form and add this code, you'll see it should work. Maybe you're having problems within the IF clause?
Besides, you don't need to select the shape prior to disabling it; just disable it right away.
Private Sub UserForm_Initialize()
CommandButton1.Enabled = False
End Sub
I know this is old, but got to this thread trying to solve my problem, and found a solution that wasn't mentioned here. So in case someone gets here like I did, and this didn't quite get them where they needed to go, I thought this might help.
I had a userform with a drop down box called cmdADAMFields, and I didn't want my submit button called FieldsSubmitButton to be enabled until I selected something from the dropdown box.
I had to break up my argument into two different private subs vs one larger If-Then-Else statement.
First, I put:
Private Sub UserForm_Activate()
If cmbADAMFields.ListIndex = -1 Then FieldsSubmitButton.Enabled = False
End Sub
Then when for my pulldown's private sub when it's value changed I wrote:
Private Sub cmbADAMFields_Change()
FieldsSubmitButton.Enabled = True
End Sub
The proper place for setting Enabled property is in Activate event (associated with Show method) and not Initialize event (associated with Load instruction).
The below code disable the button CommandButton1 when AL10 cell >= 10.
Private Sub UserForm_Activate()
CommandButton1.Enabled = ( Sheets("DATA").Range("AL10") < 10 )
End Sub
For buttons you can choose between normal buttons (property Enabled=False and property Visible=true), disabled buttons (property Enabled=False and property Visible=true) and invisible buttons (property Enabled=False and property Visible=False), that it is a cleaner interface, in most cases.
Concerning text boxes, besides normal, disabled and invisible status, there is a locked status, that is enabled and visible, but cannot be user edited. (property Locked = True)
A locked control only can be changed by VBA code. For instance, someone can includes date text boxes, that it's filled using a secondary popup date form with Calendar control.

Can't close userform

Let me set up the environment.
This is VBA code running in Excel.
I have a userform that contains a msflexgrid. This flexgrid shows a list of customers and the customer', salesperson, csr, mfg rep, and territories, assignments. When you click in a column, let's say under the Territory column, another userform opens to show a list of Territories. You then click on the territory of your choice, the userform disappears and the new territory takes the place of the old territory.
This all works great until you click on the territory of your choice the 'Territory' userform does not disappear (it flickers) and the new territory does not transfer the underlying userform.
I should mention that when I'm stepping through the code it works great.
I'm assuming it has something do to with the flexgrid as all the other userform (that don't have flexgrids) that open userform work just fine.
Following is the some code sample:
** Click event from flexgrid that shows Territory userform and assignment of new territory when territory userform is closed.
Private Sub FlexGrid_Customers_Click()
With FlexGrid_Customers
Select Case .Col
Case 0
Case 2
Case 4
Case 6
UserForm_Territories.Show
Case Else
End Select
If Len(Trim(Misc1)) > 0 Then
.TextMatrix(.Row, .Col) = Trim(Misc1)
.TextMatrix(.Row, .Col + 1) = Trim(Misc2)
End If
End With
End Sub
** The following Subs are used in the Territory userform
Private Sub UserForm_Activate()
Misc1 = ""
Misc2 = ""
ListBox_Territory.Clear
Module_Get.Territories
End Sub
Private Sub UserForm_Terminate()
Set UserForm_Territories = Nothing
End Sub
Private Sub ListBox_Territory_Click()
With ListBox_Territory
Misc1 = Trim(.List(.ListIndex, 0))
Misc2 = Trim(.List(.ListIndex, 1))
End With
Hide
UserForm_Terminate
End Sub
I know this a long winded explanation but I'm a fairly decent VBA programmer and this has me stumped.
Any help would be greatly appreciated.
I'm not going to say what you're doing is wrong (in that it won't ever work), but it scares the heck out of me. This is not the way I'd deal with forms.
Firstly, you're using UserForm_Territories (the class/form name) to refer to an implicitly-created instance of the form. This is something I've always avoided doing. I would always create an instance of a form explicitly, so instead of:
UserForm_Territories.Show
I would do:
Dim oTerritoriesForm As UserForm_Territories
Set oTerritoriesForm = New UserForm_Territories
oTerritoriesForm.Show vbModal
' get the values from the form here
Unload oTerritoriesForm
Next, and much more worryingly, you're subverting the UserForm_Terminate behaviour by calling it explicitly. Why you're doing this I can't imagine, unless you thought that it would work around your stated problem. My advice: don't do that.
Worse, you're attempting to assign to the implicitly-created instance of the form within that Terminate method. You shouldn't be doing that, either. I'm surprised that even compiles.
It seems like you're trying to force the implicitly-created instance of the form to mimic an explicitly-created one. In which case, create it explicitly, as shown above.

Resources