Excel Drop Down Box with Formula - vba

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?

Related

Update drop down lists with the same choice clicking in the active list

I have some drop down lists in the same row. All of them have the same options in their list.
To set all the lists drop down with the same selection I have to click one by one in all of them.
I tried with Crtl+Intro but it doesn´t work. I also tried using in this the method keysen but this only works with regular cells, not with list drop down.
I tried with the event Worksheet SelectionChange and I had some results, but I have not managed to change the value of the list drop down that are not active. Here is some sample code:
If Target.Cells.Count > 1 And Target.Rows.Count = 1 Then
Dim cell As Range
For Each cell In Selection
cell = ActiveCell.Value
Next cell
End If
With this code it is necessary to have some value in the active cell before selected. If you change the value later doesn´t work.
I tried again with the event Worksheet Change but that was worst, because the different lines that I used always generated infinite cycles, even if I used close cycles to repeat the action only the number of cell selected.
So, I am looking for some code to change all the list drop down selected only changing the value in the active cell (active list drop down). Clicking once and change all of them with the same value.
Assume I have three drop down menus in A1, B1, and C1.
This code sets all values the same based on changing the drop down in A1:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim dd1 As Range, dd2 As Range, dd3 As Range
Set dd1 = Range("A1")
Set dd2 = Range("B1")
Set dd3 = Range("C1")
If Not Intersect(Target, dd1) Is Nothing Then
dd2 = dd1.Validation.Parent
dd3 = dd1.Validation.Parent
End If
End Sub

Excel VBA Compare cell value to list and overwrite value in separate sheet

In a workbook I have, users either manually enter an account code or select one from a list and the account codes are placed in column C (C7:C446) in a sheet called "JE". The account codes look like this ####### - ### - ## - ######. In column D (D7:D446) in sheet "JE", there is a formula that captures the last 6 digits of the account code. In a sheet called "required_refs", there is a list of 6 digit codes in column A. If the value in the D column in sheet "JE" equals any of the values in column A of "required_refs" sheet, I would like the value in the D column cell to overwrite the cell value in cell D1 in a separate sheet called "references" (I know that may have been confusing, sorry)
Example: if the value of D25 matches any of the values listed in column A of sheet "required_refs", upon double clicking a red colored F25 cell, put the value of D25 (of sheet "JE"), and put it in cell D1 on sheet "references".
I've taken a crack at it as best I know how. I've placed this code in sheet JE:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim project As Range: Set project = Range("D7:D446")
Dim param As Range: Set param = Worksheets("references").Range("D1").Value
For Each cell In project
If project.Value = Worksheets("required_refs").Range("A:A").Value Then
Call gotoRef_ 'macro that simply selects/navigates to the required_ref sheet
project.Value = param
End If
End Sub
Thanks so much in advance for any suggestions on how to complete this. I can elaborate on this further if needed.
This will do what you want:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Range("F7:F446")) Is Nothing Then Exit Sub
Dim varReference As Variant
varReference = Columns("D").Cells(Target.Row).Value2
If Not IsError(Application.Match(varReference, Worksheets("required_refs").Columns("A"), 0)) Then
Worksheets("references").Range("D1").Value = varReference
End If
End Sub
Important Points:
Whenever working with event handlers, always limit the scope of the target range in the first line. Otherwise, it might not work correctly or it could slow done your spreadsheet.
Make sure your JE sheet column D values and required_refs sheet column A values are all either text or numbers. Otherwise the values won't be compared correctly.
Note the usage of Application.Match() instead of WorksheetFunction.Match() to access the worksheet function. This, coupled with the use of a Variant type variable, allows us to trap the error that occurs if the match fails.
You can always do this on the sheet. Consider the MATCH function. See here for how to use MATCH.
Or another great tool if you're searching for something in a table associated with a value in another column (not your case I don't think)--VLOOKUP formula. Place this formula in the D cell of the sheet you want to place the numbers in. VLOOKUP is in the following format:
=vlookup(lookup value,table_array,column index number, [range lookup])
The lookup value is the 6 digit code you're looking for (on the JE sheet)
The table_array is simply selecting the values you want to search for (required_refs sheet)
The column index number would be one, since the table only has 1 column. It's basically the column number of the value you're looking for.
And range lookup is for if you think there might be more than one place where it matches.
For your case I think it would look like this:
=vlookup('JE'!D1,'required_refs'!A1:A,1,FALSE)
Then just lock the values you want to keep and click and drag down.
Explanation for VLOOKUP here

Copy rows based on cell value and paste on a new sheet

Check This
I need a help. I want to copy whole cell from A sheet name "Components" only if value in Column C is > 0 to a new Sheet name "Load list"
Can someone please give me the macro code for this?
on your new sheet you can add this condition the cell or range of cells:
=IF(Components!C5>0,Components!A5)
where C5 has thevalue to compare, and A5 has the value copy if the condition happens.
Right in my swing!
The formula given by #sweetkaos will work fine, in case you want to replicate the data as it is with blanks where data is not found.
I will imagine a slightly more complicated situation. I am assuming you want just one line in the next format as is shown in your image.
Also conveniently assuming the following:
a. both sheets have fixed start points for the lists
b. 2 column lists - to be copied and pasted, with second column having value
c. Continuous, without break source list
d. basic knowledge of vba, so you can restructure the code
Here is the code. Do try to understand it line by line. Happy Excelling!
Sub populateLoadList()
'declaring range type variables
Dim rngStartFirstList As Range, rngStartLoadList As Range
'setting values to the range variables
'you must change the names of the sheets and A1 to the correct starts of your two lists
Set rngStartFirstList = Worksheets("Name_of_your_fist_sheet").Range("A1")
Set rngStartLoadList = Worksheets("Name_of_your_second_sheet").Range("A1")
Do While rngStartFirstList.Value <> ""
If rngStartFirstList.Offset(1, 0).Value < 0 Then
Range(rngStartFirstList, rngStartFirstList.Offset(0, 1)).Copy
rngStartLoadList.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Set rngStartLoadList = rngStartLoadList.Offset(1, 0)
End If
Set rngStartFirstList = rngStartFirstList.Offset(1, 0)
Loop
End Sub
Basically what i want is ... if Value on C is >0 i want whole column 10 copied to that new sheet .... not only that cell

Highlight unique values based on another range

Column 1 is in Sheet1 and column 2 is in Sheet2. If the value is not found , then highlight that cell. I am trying to do a vlookup comparing two columns. I think the Syntax is incorrect. Please see my code I was trying below:
Option Explicit
Sub VlookupColoums()
' declarations
Dim lookFor As Range
Dim srchRange As Range
Dim I As Long
Dim vtest As Variant
' start
Set lookFor = Sheets("Sheet1").Range("A13").End(xlUp)
Set srchRange = Sheets("Sheet2").Range("A2").End(xlUp)
vtest = Application.VLookup(lookFor.Rows.Count, srchRange.Rows.Count, 2, False)
' process
For I = 1 To lookFor.Rows.Count
If IsError(vtest) Then
srchRange.Interior.Color = 4
Else
Exit Sub
End If
Next I
End Sub
Assuming you have data on Sheet1!A1:A15 and Sheet2!A1:A10.
Also assuming you want to highlight unique cells (ones withouth at least one identical in the other list) on Sheet2.
Basically you want to format all the cells that if counted on the other list comes up with 0. The steps:
Select all the cells to be evaluated on Sheet2
Go to Home/Styles/Conditional Formatting
Select New Rule, then Use a formula to determine...
Enter this formula: =COUNTIF(Sheet1!$A$1:$A$5,A1)=0
Click on the Format button, and set up a formatting for the unique cells
OK
Profit. :)

VBA applying function to each cell in range

I need to write macro or function or whatever in VBA, what will apply a function with arguments (e.g. vlookup) on a rangeof cells. I thought it can be done by macro, but there I could not use arguments for vlookup, so I dont know any way how to do it. Is it possible?
For example:
I want to have this:
vlookup(A1;G1:H50;2;0) in cell B1 and
vlookup(A2;G1:H50;2;0) in cell B2 and so on, to e.g. B10
but I want to write formula only once and let other cells to be filled automaticaly.
Thanks a lot.
If I understand you correctly, here is one way (you'll have to change the delimiter to match your country settings, and adjust where you want the formula to go, I just put in B1:B10 as an example):
Sheet1.Range("B1:B10").Formula = "=vlookup(A1,$G$1:$H$50,2,0)"
This bit of code will write the formula to the range B1:B10 on sheet1, which has the same effect of putting the formula in the B1 and then "dragging" it down to B10. What makes this work is that Excel has the built in functionality of auto-incrementing a formula references based on whether or not the range is preceded by a $ symbol.
If a column reference has a $ in front, it will not increment as the formula is dragged across columns. If the $ is in front of the row reference, it will not increment as the formula is dragged down.
So looking back at my proposed formula, you can see that the A1 will increment as the formula is dragged to B2, B3, B4, etc...auto-incrementing the look up value to be cell A2, A3, A4, respectively. The look up range does not change at all because both the column and the row references are preceded by a $.
If you run the code I gave you, you'll see that you should have the expected results of only writing one formula, but changing the look up range through the built in auto incrementing functionality.
--------------------More edits based on comments--------------------
To do what you want, you don't need VBA at all (even though you initially requested a VBA / macro solution). You can put the formula in a cell and drag it down to how ever far down you want it to go. Please take a look at this link to see if it helps answer your questions:
How to fill data automatically in Excel
You could use Application.VLookup just like this following this example http://www.exceltrick.com/formulas_macros/vlookup-in-vba/:
Sub SetValues(columnToChange As String, columnToLookup As String, range As String, startColumn As Integer, endColumn As Integer)
For number = startColumn To endColumn Step 1
valueLookup = columnToLookup + CStr(number)
valueToChange = columnToChange + CStr(number)
Sheets("yourSheetName").Range(valueToChange).value = Application.VLookup(valueLookup, range, 2, 0)
Next number
End Sub
If you want to call them, create another subroutine without parameters that you can call from a button click for instance.
Sub DoStuff()
On Error GoTo ErrorHandler
Dim valueLookup as String
Dim valueToChange as String
Dim range as String
Dim firstColumn as Integer
Dim lastColumn as Integer
Label1:
valueLookup = InputBox("Enter the column to lookup")
valueToChange = InputBox("Enter the column to change")
range = InputBox("Enter the range of the lookup")
firstColumn = CInt(InputBox("Enter the first column number to lookup"))
lastColumn = CInt(InputBox("Enter the last column number to lookup"))
Call SetValues(valueToChange, valueLookup, range, firstColumn, lastColumn)
Exit Sub
ErrorHandler:
MsgBox("One value has an error in it.")
Resume Label1:
End Sub