I'm using a "worksheet_selectionChange" event to fire a macro whenever a cells within certain ranges are selected.
Public Sub Worksheet_SelectionChange(ByVal Target As Range)
Select Case Target.Cells.Offset(-???,0).Value
Case "LABEL_1"
Tenor = "2W"
Call MyLameMacro()
Case....
End Select
End Sub
Those ranges look like little matricies:
If the user selects any of the cells underneath label, I want VBA to lookup whatever the label is at the top. Using offset would work if I knew exactly how many rows up to Label, but its not constant....
Is there another way to go about that?
Thanks - KC
Barring further information about the layout ... you can use formatting to build your own search algorithm. This will slow down if it has to go through thousands of lines (find another way if your data set is that large).
You'll have to replace "labelColor" and "notLabel" with the background color of the label rows. This is assuming the above picture is accurate, and "Label" is highlighted. To find the value to replace them with, simply select the cell in question, then type "debug.print selection.interior.color" into the immediate window in VBA.
By placing the label value and the origin address in parentheses after your lame macro, you can preserve those values in the macro.
I did not test this. In order to do so I would have to guess at the setup of your workbook ... but an approximation of this code should work for you.
Public Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim i As Integer
i = 0
searchLoop:
If i > 100 Then
MsgBox ("Infinite loop. Click OK to stop")
Exit Sub
End If
If Target.Offset([-i], 0).Interior.Color = labelColor Then Call MyLameMacro(Target.Offset([-i], 0), Target.address)
If Target.Offset([-i], 0).Interior.Color = notLabel Then
If Target.Offset([-i], 0).Value = "Value" Then Call MyLameMacro(Target.Offset([-i], [-1]).Value, Target.address)
i = i + 1
GoTo searchLoop
End If
End Sub
Related
I am currently doing my final year project and it make use of excel VBA whereby I am bad at it. I am really hope someone could guide me through the problem that I am facing.
As for now, I am hoping that I can use a drop down list to filter my table whereby it only shows the particular department and weeks I want to show.
From the image below,
From the range("C7:L26"), whenever I filter cell(F2) or cell(J2), it will leave the data that I want from the dropdown list.
For example, if cell(F2) = 2 and cell J2 = e,
From range("C7,L26"), it will only show department with value "e" and have week 2 in it. As for cells that does not have the department value or week value, it will be cleared or blank.
I also hope that if it is possible to press a button to return the table back to default.
Do guide me and I really need your help!! Thank You
[1]http://imgur.com/GNGyh91
[2]http://imgur.com/uuh2Y1u
As for now I have this as my codes that I've learnt from a user #PeterT
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:AW28")) Is Nothing Then
Dim legendWS As Worksheet
Dim legendcell As Range
Set legendWS = ThisWorkbook.Sheets("Legend")
Set legendcell = legendWS.Range("A2:A18").Find(Target.Value)
If Not legendcell Is Nothing Then
Target.Interior.Color = legendcell.Interior.Color
End If
End If
End Sub
End Sub
I am new to VBA and have only recently been developing my excel skills.
I have created 3 different scenarios for an investment project situation, these scenarios appear in cell "h13" as a drop down box with three options being available, best case/worst case/base case.
When you select each scenario the various outputs will change on the sheet and I have set up the following code to change the outputs and display the relevant ones according to the scenario:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$H$13" Then
ActiveSheet.Scenarios(Target.Value).Show
End If
Now, what I want to achieve is the following:
In Cell E13 I have a numeric value that is my main concern (I should note this is an NPV Formula). Every
time we change scenario this value obviously changes.
I would like
to create a summary table that is simply something like this:
Scenario 1 = x Scenario 2 = y Scenario 3 = z So Ideally what I want
to do is, when we select scenario 1 we copy the value from E13 to say
B21. When we select the next scenario E13 will obviously change,
however I would like the copied value of B21 to remain the same, and
now the new Scenario 2 value to be displayed in B22.
I have no real idea how to go about this? I have tried adding this on the bottom but the values do not remain 'static'
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("h13")) Is Nothing Then
Range("E13").Copy
Range("B21:B23").PasteSpecial xlPasteValues
End If
End Sub
Now I think I know that I need to create a reference so that it would read something like when e13=y then copy, next e13=x copy and loop? it until all outcomes have occured. Not sure how to do it though.
Any help would be appreciated, I have tried to read up on this as much as possible but I cannot really exactly pin point what I need in code terms as I am very new to this
Thanks in advance.
This solution shows the results in a "range\table" located at B20:D23 (see pictures below)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rTbl As Range, lRow As Long
Application.EnableEvents = False 'To avoid triggering again when table is updated
If Target.Address = "$H$13" Then
Rem Filters value in target range
Select Case Target.Value2
Case "Base case", "Best case", "Worst case" 'Change as required
Case Else: GoTo ExitTkn 'Value is not in the list then exit
End Select
Rem Show Scenario
ActiveSheet.Scenarios(Target.Value).Show
Rem Update Results
Set rTbl = Range("B21").Resize(3, 3) 'Change as required
With rTbl
lRow = WorksheetFunction.Match(Target.Value, .Columns(1), 0)
.Cells(lRow, 2).Value = Range("E13").Value2 'Updates result - Change as required
.Cells(lRow, 3).Value = Range("D13").Value2 'Updates scenario variable - Change as required
End With
End If
ExitTkn:
Application.EnableEvents = True
End Sub
Suggest to read the following pages to gain a deeper understanding of the resources used:
Select Case Statement,
With Statement
Hi I have an excel with a drop down box whose list has 3 cells. One of these cells contain a formula. The problem is this formula is dependent on data in another cell and when this data changes the calculated value changes. The value is automatically update in the list where it was chosen from but I will manually have to go back to the drop down box and change it. How can I have the value be updated automatically. Willing to look at a VBA solution if need be
Put the following into the worksheet module. It assumes that the cell with validation applied is G9, and the second option of the list is the formula.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address(False, False) = "G9" Then
If Target.HasFormula Then Exit Sub 'or else infinite loop
Dim ListRange As Range
Dim FoundIdx As Variant
Set ListRange = Me.Evaluate(Me.Range("G9").Validation.Formula1)
FoundIdx = Application.Match(Target.Value, ListRange, 0)
If Not IsError(FoundIdx) Then
If FoundIdx = 2 Then
Target.Formula = ListRange(2).Formula
End If
End If
End If
End Sub
Note that this will not work if the formula might have the same value as any of the other options!
I couldn't reproduce your issue. Here is what I did:
Populate 2 cells with a random value and a third cell with a formula (columns B3, B4, B5)
Define a Name Range with these 3 cells called it Options
Create a drop down using Insert/Form Controls/Combo Box
Set the input range of the drop down to Options
Change the cells value to get the formula give different results and the new values are reflected on the Options list and the Drop Down.
Is this what you are doing?
I have this function which is trying to detect when a particular cell value changes. The problem is, if the user selects the whole spreadsheet and presses delete, I get an overflow in my check that the range is only a single cell:
Public Sub Worksheet_Change(ByVal Target As Range)
'Overflow can occur here if range = whole spreadsheet
If Not IsError(Int(Target.Cells.Count)) Then
If Target.Cells.Count = 1 Then
If Target.Cells.Row = 4 And Target.Cells.Column = 1 Then
Sheets("X").Cells(5, 1).Calculate
End If
End If
End If
End Sub
Is there a more elegant way that I can get this code to only run, when a single particular cell value is changed? (with no overflows, problems when I clear the whole worksheet etc)?
I'm assuming you are on Excel 2007+ since the number of rows and columns increased dramatically in those versions. You might have better luck checking to make sure both the row and column count = 1, since those maxes will be much lower than the product of the two (ie, the cell count):
If Target.Rows.Count = 1 And Target.Columns.Count = 1 Then
Use CountLarge instead of Count
Private Sub Worksheet_SelectionChange(ByVal target As Range)
If target.Cells.CountLarge > 1 Then Exit Sub
'Code...
End Sub
See: MSDN Range.CountLarge Property (Excel)
In Excel, I have three columns:
column1, column2, column3
I am entering data into excel using a barcode scanner that is attached to an IPAD. The barcode scanner sends ENTER after every scan. I believe that I can set excel up such that ENTER would cause the next column to be selected (instead of the next row)
However, I do not know how to have it go to the next row after there is an ENTER detected in column3. Right now I have this:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Column = 3 Then
If Target.Value = "{enter}" Then
MsgBox "SDf"
End If
End If
End Sub
But Target.Value detects only the string inside the cell, it does not detect what has been pressed.
How do I get the next row to be selected after ENTER is detected in column 3?
You don't need vba code for this.
The easiest way is to unlock the cells in those three columns and lock the rest of the cells. Once done, protect the entire sheet. However when protecting, ensure you uncheck the option called Select Locked Cells See screenshot. The yellow columns are unprotected.
The next step is to set excel so that after the data is entered and Enter key is pressed, the cursor moves to the next column. You can do that (Say in Excel 2010) from the File TAB | Options | Excel Options | Advanced
When the cursor reaches the last column and data is entered and the enter is pressed, the cursor will automatically move to the next row. See snapshot.
HTH
In addition to Siddharth's excellent suggestion, here's an event-based approach:
Private Sub Worksheet_Change(ByVal Target As Range)
'named (contiguous) range on input sheet
Const DATA_NAME As String = "DATA"
Dim rngData As Range, numCols As Long
If Target.Cells.Count > 1 Then Exit Sub
Set rngData = Me.Range(DATA_NAME)
numCols = rngData.Columns.Count
If Not Intersect(rngData, Target) Is Nothing Then
If Target.Column < rngData.Columns(numCols).Column Then
Target.Offset(0, 1).Select
Else
Target.Offset(1, -(numCols - 1)).Select
End If
End If
End Sub