Excel VBA - Select a cell in a highlighted range - excel

Is it possible to select a specific cell in a range that changes depending on what cells are highlighted.
So if i Had;
Range("C1").Value = Application.WorksheetFunction.Sum(Selection)
It would sum the entire highlighted area and put the value in C1. Is it possible to only select some cells in the highlighted area. I know it sounds dumb, i realise can just highlight the cells i need but this is just a simplified version of the problem I've got.
What i'm asking is, is there a way in code to say;
"In the highlighted range, select the cell that is 2 columns to the right and 4 columns down from the top left boundary of the range"
Thanks

The Code for your question:
"In the highlighted range, select the cell that is 2 columns to the right and 4 columns down from the top left boundary of the range"
Selection.Cells(1).Offset(4,2).Select

in your case being Selection a Range you can use its methods/properties:
Range("C1").Value = Application.WorksheetFunction.Sum(Selection.Cells(5,3))
since Cells(5,3) reference a cell 2 columns to the right and 4 rows down offset the selection top-left one

You may be able to use the Worksheet_SelectionChange Event and examine the Target reference.
For example paste this test code into some sheet class:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Address = "A1" Then Exit Sub
Range("A1").Value = WorksheetFunction.Sum(Target)
End Sub
Something like this - obviously you're going to have all kinds of checks in there for Errors and the likes.
I'd also look at some way of disabling the code since you're going to have Events firing all over the place. Depends on your requirements.

Related

Excel selecting a number of cells below selected cell shortcut options

In Excel, I would like to select a cell and then copy the contents to n number of cells below. Instead of using the "fill" drag option since the number of rows will be fairly large and require scrolling and then stopping at the correct cell I was looking for other options.
I am currently doing the the following:
In excel I select a cell and then on the top left corner it shows the cell (i.e. A1). Then to select the number of cells below it, I modify the top left box to a range such as A1:A10 which selects the range of cells. See attached image. I then use the shortcut key "Ctrl-D" which copies the first cell to the other cells.
Is there a way instead of mentally calculating the ending cell number, I can do something that effectively works "A1 + 10" in this box to select 10 cells below to select the A1:A10 range?
How about this way? Enter your formula in cell 1. Enter the number of copies (including the original) you want of it in the cell below it. Double-click on the number you entered and the formula is filled down.
To try, install the procedure below in the code module of the worksheet on which you want the action. (That's a module Excel set up when you created the sheet. Don't install the code in a standard code module that you have to insert yourself.)
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Const TriggerClm As String = "A"
Dim R As Long
With Target
If (.Column = Columns(TriggerClm).Column) And (.Row > 1) Then
R = Val(.Value)
If R Then
With .Offset(-1)
If .HasFormula Then
.Resize(R).FillDown
.Select
Cancel = True
End If
End With
End If
End If
End With
End Sub
You may wish or have to tweak the code. For example, the action is limited to column A. Change the constant at the top of the code to identify the column you prefer, or change the limits to better suit your requirements. The code also checks if Cell #1 contains a formula. If that isn't what you want to fill down that condition will have to be revised.
Last, but not least, the code selects Cell#1 (the one that contained the number is over-written). That may not be the best choice. You can modify the code to select a place in your worksheet where you will continue working.

How to change a cell value based on active/selected cell

I am having a list of names in a Range A2:A77, in the worksheet name called Manual. whenever i choose a name, that is when a cell gets selected from the range, that active cell value should get reflected in the cell C1. Also, the macro should not work incase if i selected else where, other than the given worksheet or range.
I have googled alot but nothing seem to be matching my criteria, so i'm here, hoping for a better solution. You may ask me to achieve this by using data validation, but for that i will have to do multiple clicks and scrolling work to be done everytime. so to avoid that i'm looking for vba code to minimize the work and time.
Thank You.
I am only just learning VBA at the moment so this could be some very horible code but here goes.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cells As Range
Set cells = ActiveSheet.Range("A1:A27")
If Not (Intersect(Target, cells) Is Nothing) Then
ActiveSheet.Range("C1").Value = Target.Value
End If
End Sub
Worksheet_SelectionChange is called if the selected cell in the sheet changes then using the test from InRange that I found here: VBA test if cell is in a range test if the cell is within the defined range then set the values.
Edited as sugested by #Vitaliy Prushak in comments.

Excel, Add auto Sequence number

I need to ad the next sequence number in Column A automatically when I fill enter the next value in Column B. This sounds confused. Just see the snap so you will get the clear picture.
This should be done without usual dragging option. Is there any way
Make the Value of A1 equal to 1 and then from the A2 use the formula:
=IF(B3<>"",A2+1," ")
Drag this formula for the whole column.
In my solution I have a drag, but it is to define the formula for each of the fields. (I'm not sure if is this you are trying to avoid when you say
without the usual dragging option
)
You may achieve this using macros. Formula will increase the file size and processing time.
Right click on the sheet name on sheet tab-->select view code-->paste below code--> save file as macro enabled workbook.
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo step
If Target.Column = 2 And Target.Value <> "" Then
Target.Offset(0, -1) = Target.Row - 1
End If
Exit Sub
step:
Exit Sub
End Sub
You can also do this without using macro and formula:
Type first 2 value to the cell to establish the pattern
highlight the cell range
Under Home tag -> select Fill -> choose Series
Follow the image and Select OK
If you convert your table to a List ("Table") and use a formula for the first column, that formula will "auto-extend" as new values are typed in under "Item"

Solve for value without using Solver

I currently have the following in excel for other users.
The Number column does not change. Users will input values in Multiplier 1 and Multiplier 2 columns and they will get a value in Outcome column.
Is there an automatically way where the user can also input a value in Outcome column and the Multiplier 1 column will change?
Currently Number and Outcome column are protected, will I need to unprotect the Outcome column?
I recommend you use some VBA code using the Sub Worksheet_Change(ByVal Target as range) in the worksheet.
If the user enters a value in D2 it will put the formula "=D2/(A2*C2)" in B2
If the user enters a value in B2 it will put the formula "=A2*B2*C2" in D2
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Cells.Count > 1 Then Exit Sub
On Error GoTo LastLine
If Not Intersect(Target, Range("D2")) Is Nothing Then
Range("B2").Formula = "=D2/(A2*C2)"
ElseIf Not Intersect(Target, Range("B2")) Is Nothing Then
Range("D2").Formula = "=A2*B2*C2"
End If
LastLine:
Application.EnableEvents = True
End Sub
This can be done. Begin by noticing that your formula is so simple that you
Can easily solve for multiplier1 as a function of:
outcome divided by (number times multiplier2)
Next get tricky by adding a 1 pixel wide column that will contain your formula
for outcome to the right of (now an input not a formula) the original
outcome column.
Similarly add a 1 pixel wide col to the right of multiplier1 that contains
your new formula for multiplier1. Adjust data validation on original input
cells for multiplier1 and outcome to allow only one of the two to be
entered at a time (use isblank function appropriately in an excel custom data
validation rule for each cell).
Finally right align the two 1 pixel wide cells so that their calculated values
appear within the corresponding enterable cells when they are blank.
Yes it's tricky but it works.
Sorry this is just an outline but I have used this in an application and it
works great. No vba, so undo redo don't break. Try it you'll like it.

How to highlight active row in excel and then return to base background color in VBA

How do you highlight an active row in excel in VBA. and then when another row is selected, return that row to base background color, and highlight the new row.
Also how to clear all rows highlighted, using a clear button on the user form.
so there are tow question here, one to high light and unhighlight active rows, and the other to just clear all high lights by pressing a clear button on the form.
I know I can highlight a row using Ret.EntireRow.Interior.ColorIndex = 6 but i cant find code to unhighlight.
Thanks for your help.
You can use your 'clear all' functionality before changing the color of the row of the cell that you navigated to.
Open the VB Editor and right click --> view code on the worksheet that you want the row highlighting to take place.
Paste in this code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Me.Range("A1:XFD1048576").Interior.ColorIndex = 0
Target.EntireRow.Interior.ColorIndex = 6
End Sub
This code operates as follows: whenever a user changes his or her selected cell(s) on the sheet, the code will first clear the existing highlighting away in the entire sheet and then will apply new highlighting to the row of the target cell the user has moved to.
This line of code:
Worksheets("YourSheetName").Range("A1:XFD1048576").Interior.ColorIndex = 0
Will clear the colors from all cells in the worksheet.
You may want to limit the Range("A1:XFD1048576") to the usable range on your workbook as this will increase performance. On my machine I see a very subtle, but still noticeable, delay in the colors when I move the cells (because I am clearing all cells in the sheet instead of just the ones I want). If you do this, you probably wouldn't want to use the .EntireRow attribute, instead you would have to enumerate how far along the workbook you want the row to be highlighted.
Update
Try this code below, which eliminates the need to clear the entire worksheet. I used .ColorIndex=xlNone instead of setting it to 0 which should preserve your table formatting. I tested in Excel 2010 and I formatted some data as a table, it highlights the correct row and unhighlights the other row as well as leaving the table formatting in tact.
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Static rr
If rr <> "" Then
With Rows(rr).Interior
.ColorIndex = xlNone
End With
End If
r = Selection.Row
rr = r
With Rows(r).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End Sub
The trick is using Static. This allows the variable to continue to exist after termination of the procedure, so it remembers the last row it highlighted and then performs the un-highlight action accordingly.
The procedure first checks to see that rr is set, if it is not then it moves on, if it is then rr represents the row that was previously highlighted.
This can be done without changing the base background color,
In 2 steps,
Set up a conditional formatting rule that highlights an entire row if a certain formula is true.
In the formula field, enter this formula:
=OR(CELL("row")=CELL("row",A1))
Write a macro that recalculates the selected cell(s) when a new selection is made.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Target.Calculate
End Sub
Hit Alt + F11 to get back to Excel and you'll have the active cell's row highlighted with the format you chose, without changing the base colors of the cells.
For detailed explanation visit,
highlighted the entire row of the active cell.

Resources