excel , Excel - select a cell based on adjacent cell value

## Question:

Tag: excel

I have the following excel spreadsheet and I am trying to work out how I can write a formula in order to provide the values in column D.

In each row, there is a test date, I am trying to calculate the day difference from each test date to the principal date, specific to each subject.

I assume this would involve selecting the principal test date based on the value in column C and I am not sure how I can do this.

Any help would be appreciated.

``````A            B           C                 D
Subject      TestDate    Principal date    Day difference from Principal  date
Subject 1    01/12/2014                    -3
Subject 1    02/12/2014                    -2
Subject 1    03/12/2014                    -1
Subject 1    04/12/2014   Yes               0
Subject 2    07/12/2014                    -1
Subject 2    08/12/2014   Yes               0
Subject 2    11/12/2014                     3
Subject 3    17/12/2014                    -1
Subject 3    18/12/2014   Yes               0
Subject 3    24/12/2014                     6
``````

The logic here is: (1) Find the date for each subject that is the principal date, and return it for each row; and (2) subtract this date from the current date in `col B`. (2) is easy, but (1) requires a way to match the value in `B` on both `Subject` and `Principal Date`. You can do this with an `INDEX-MATCH` function with multiple `MATCH` criteria.

With your data in `A2:C11` and the column headers in `row 1`, enter this formula in `D2` and fill down:

`{=B2-INDEX(\$A\$2:\$C\$11,MATCH(1,(\$A\$2:\$A\$11=\$A2)*(\$C\$2:\$C\$11="Yes"),0), 2)}`

Note that you need to enter it as an array formula using CtrlShiftEnter.

The logic behind the `INDEX-MATCH` function is:

• `A2:C11` is your entire raw data table; the function looks over this entire table.
• Note that you can include headers if you want, which can be useful in defining your lookup column by a matching column header name. If you do this, you need to make sure all of your arrays are of the same dimensions (i.e., if your data table is `A1:C11`, your columns in the `MATCH` function need to start in `row 1` as well).
• The `MATCH` function looks for a value of `1` from the lookup array provided by multiplying multiple logical conditions. It will evaluate whether `A2=A2`, `A3=A2`, `A4=A2`, etc. and create a column of `TRUE`/`FALSE` values. It will then do the same for `C2="Yes"`, `C3="Yes"`, etc. The product of the logical arrays will be `1` any time both conditions are satisfied. (`0` tells `MATCH` to look for an exact match.)
• `2` tells the `INDEX` function to find the value in the second column (`B`) in the row specified by the `MATCH` function -- i.e., where both conditions are met.

This value is then subtracted from the value in `B2` to give the date difference.

As noted in the comments, this formula can also be simplified to index only the desired lookup column:

`=B2-INDEX(\$B\$2:\$B\$11,MATCH(1,(\$A\$2:\$A\$11=\$A2)*(\$C\$2:\$C\$11="Yes"),0))`

# Related:

## Using a stored integer as a cell reference

excel,excel-vba,reference
Dim x As Integer Dim y As Integer For y = 3 To 3 For x = 600 To 1 Step -1 If Cells(x, y).Value = "CD COUNT" Then Cells(x, y).EntireRow.Select Selection.EntireRow.Hidden = True End if If Cells(x, y).Value = "CD Sector Average" Then Cells(x, y).EntireRow.Select Selection.Insert Shift:=xlDown Cells(x +...

## C# code to add hyper link in excel sheet

c#,excel
Hi I am having an excel file containing multiple sheets. One of the sheets will contain the hyperlink for other sheets. While using the following code I have successfully added the link but when I click on the link it gives error **"Refrence not valid"** Code snippet: private void AddHyperLink(Workbook...

## Ordering values from random list in Excel

excel
is there any possibility how to order values from cca 100 rows into table according to two criteria? Compare name and compare Category, or is it bad approach? Lets say i have a list of people: Name Category Value Carl A 10 Carl B 17 John A 11 Jane A...

## How to convert excel data to json at frontend side

excel,user-interface
I want to convert some excel data to JSON. Plan is to get my excel file from D drive, read data and make some UI for this. Can any one please help me out? Data is like this :- country year 1 2 3 4 Netherlands 1970 3603 4330 5080...

## 12 Characters Including leading and following zeros

excel
I am finding this difficult to explain, but ultimately I am wanting a cells value to be 12 characters long including +/- a decimal point and following zeroes. Examples are 1200 would become +1200.000000 -20 would become -20.00000000 99999999 would become +99999999.00 I have tried FIXED, LENGTH, and formatting rules...

## Comparing cell contents against string in Excel

string,excel,if-statement,comparison
Following is my table file:*.css file:*.csS file:*.PDF file:*.PDF file:*.ppt file:*.xls file:*.xls file:*.doc file:*.doc file:*.CFM file:*.dot file:*.cfc file:*.CFM file:*.CFC file:*.cfc file:*.DOC I need a formula to populate the H column with True or False if it finds column G in column F (exact case). I used following but nothing seems to...

## Which is faster in Excel, an if formula giving 1 or 0 instead of true/false or --?

excel
I've got a large spreadsheet that I'm trying to optimise as it has over 12,000 lines of data, with in excess of 28 columns. It currently takes a significant amount of time to execute and I'm therefore starting to pare it down. As part of this I've started looking at...

## timestamp SQL to Excel

php,mysql,sql,excel
If this is a duplicate, please let me know, I haven't found anything. I have written a php file that can read content from a database table and write it into a excel .xls file. Everything works fine except by that timestamps. In my generated .xls file every timestamp is...

## Label linked to a text box value

excel,vba,textbox,label
Good morning, I am editing an User Form on VBA Excel and I would like to show an alert if the user insert a certain value in a text box. I wrote this code: If txtbox.Value < 0 Then lbl_Alert.Visible= True Else lbl_alert.Visible=False End IF The code works properly but...

## Dates not recognized as Dates, despite format

excel,datetime
I have imported a column with many dates, but Excel will NOT read them as dates for some reason. I have looked around and tried doing "Text to Columns" and using "DMY" format. I have also tried simply changing the format of the cells to Date (also Custom 'dd/mm/yyyy'), but...

## How do I do to count rows in a sheets with filters? With a suppress lines

excel,vba,filter
I have a sheet with lots of columns, but when I filter and use count = Application.WorksheetFunction.CountA(Range("A:A")) It returns all the rows non Empty. Not only the rows I filtered....

## Find column with unique values move to the first column and sort worksheets

excel,vba,excel-vba,sorting
I have 2 worksheets with the same headers in different orders. Headers are I.D, Name, Department, Sales, Start date, End Date and a few others. What I am aiming to do is search through the workbooks in which the headers may be in different orders, find the column which has...

## Converting column from military time to standard time

r,excel
I'm trying to convert a column showing the time of road traffic accidents from military time to standard time. The data looks like this: Col1 Time..24hr. 1 1404 2 322 3 1945 4 1005 5 945 I'd then like to convert to 12hr so for '322' I'd like to make...

## Finding position of a particular string containing cell in Excel

excel,vba
I am searching for a string using below code For x = 2 To lastrow If Sheets("sheet1").Cells(x, 3) = TFMODE Then ....... 'TFMODE is the string discussed 'This particular string "TFMODE" is randomly recurring throughout 'sheet in column 3. I need to know position for a particular string in sheet1...

## Identifying cell in Openpyxl

python,excel,openpyxl
I've been working on a project, in which I search an .xlsx document for a cell containing a specific value "x". I've managed to get so far, but I can't extract the location of said cell. This is the code I have come up with: from openpyxl import load_workbook wb...

## Errors 91 and 424 when iterating over ranges in Excel VBA

excel,vba,excel-vba,range
I am an absolute VBA beginner. I have been trying to create a function that separates a large range into smaller ranges. However, when I try and iterate over the large range, I get errors 91 and 424 interchangeably. Here is the relevant bit of code: Dim cell As Range...

## Excel VBA User-Defined Function: Get Cell in Sheet Function was Called In

excel,vba,excel-vba,user-defined-functions
I have a user-defined function in Excel that I run in multiple sheets. I am trying to use Cells(i, j) to pull the value of cells by their row and column in the sheet in which my function is called. Instead, Cells(i, j) pulls the value of cell [i,j] in...

## Converting ADODB Loop into DAO

Hi I've been developing a vba project with a lot of help from examples here. I'm trying to access a MS Access database from Excel VBA and import large data sets (500-100+ rows) per request. Currently, the following loop works using ADODB however, the Range("").Copyfromrecordset line is taking very long...

## VBA - Unable to pass value from Private to Public Sub

excel,vba,excel-vba
I have a tool which I am designing to present a number of questions to a user in a set of userforms. The form will generate a score via passing an integer result from the userform to a main sub, which passes the code to a worksheet. My problem is...

## excel search engine using vba and filters?

excel,vba
I am using the following vba code to filter my rows in excel based on the value in my cell C5 Sub DateFilter() 'hide dialogs Application.ScreenUpdating = False 'filter for records that have June 11, 2012 in column 3 ActiveSheet.Range("C10:AS30").AutoFilter Field:=1, Criteria1:="*" & ActiveSheet.Range("C5").Value & "*" Application.ScreenUpdating = True End...

## Excel - Pulling data from one cell within a list

I use PowerPoint as a graphics template to type up football player names and there squad numbers. It can be a long procedure and so far following YouTube tutorials i have managed to create a form in Excel which can update the text boxes in PowerPoint at the click of...

## How to insert excel formula to cell in Report Builder 3.0

sql-server,excel,reporting-services,excel-formula,ssrs-2008-r2
There is RDL report template for SQL Server Reporting Services. I need to set value for cell in table in the report template which must be calculated from other values in the report. When the report is exported to Excel file I need to see the Excel formula in that...

## VBA - .find printing wrong value

excel,vba,excel-vba
I have two sections of code that basically do the same thing but with two different columns. The code finds the header "CUTTING TOOL" and "HOLDER" (looping through multiple files) and prints the information from those columns into one worksheet, masterfile. I was using a less efficient method of setting...

## If statement and addition

excel,excel-2010
I am trying to look if a cell value in second sheet is not equal to blank and then check the value of other cell is lesser than 3 and further update the value to 1 or 0. 1st condition if g2 cell value present in second sheet is not...

## Compare two data sets in different sheet and print difference in other sheet using excel VBA?

excel,vba
I have two data sets in two different sheet Sheet1 is my Orginal ref and sheet2 is for comparison. sheet2 data should get compared by Sheet1 and print entire mismatched row of sheet2 and highlight the cells which has mismatch data and this difference should be printed with column header...

## Excel 2013 Add a Connector Between Arbitrary Points on Two Different Groups

excel,vba,excel-vba
I'm working in Excel 2013 to (programmatically) add a straight line connector between the lower right hand corner of a rectangle that is part of a grouped shape with the endpoint of a grouped series of line segments. As it stands, I can't even seem to do this manually on...

## if condition inside Insert query in excel?

mysql,excel
i'm trying to turn my records in excel into an insert query. i've fields empty in certain situations. In such case, NULL should be inserted. I've written the formula as below but it is not working/showing error. Think i've missed something. ="INSERT INTO table_1 VALUES(" &A2 &",'" & B2 &...

## Hiding #DIV/0! Errors Using IF and COUNTIF in Excel 2010

excel,vba,if-statement
I'm working on a tracking sheet for quality reviews of work completed. I have a list of criteria to be met for which the entry can be either Y or N, or X for not applicable. Each month a number of these reviews will be done on each person. In...

## adding variables into another variable vba

excel,vba,excel-vba
Dim x As Long Dim y As Long Dim CDTotal As Double Dim CSTotal As Double Dim ETotal As Double Dim FTotal As Double Dim HTotal As Double Dim ITotal As Double Dim ITTotal As Double Dim MTotal As Double Dim TTotal As Double Dim UTotal As Double Dim TotalValue...

## NoClassDefFoundError: UnsupportedFileFormatException while using apache poi to write to an excel file

java,excel,apache-poi,writing
I am trying to write to an excel(.xlsx) file using Apache poi, I included the apache poi dependencies in my pom.xml file. But I am getting the following exception in execution. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at...

## If cell value starts with a specific set of numbers, replace data

excel,vba,excel-vba
My cell values are strings of numbers (always greater than 5 numbers in a cell, ie 67391853214, etc.) If a cell starts with three specific numbers (ie 673 in a cell value 67391853214) I want the data in the cell to be replaced with a different value (if 673 are...

## How to write formula for cell in Excel?

excel
I'm working on excel where I've few columns. I would like to make SQL insert operation from the records in sheet. There are chances of cell to be empty and this is where I am unable to continue. I need to check: if(cell is empty) insert null else insert value...

## Excel Search VBA macro

excel,vba,excel-vba
I have been given the task of searching through a large volume of data. The data is presented identically across around 50 worksheets. I need a macro which searches through all these sheets for specific values then copies certain cells to a table created in a new workbook. The macro...

## Excel vlookup expansion

excel
I currently have an excel worksheet with three columns id annotation person_id 1 yes 1 1 no 2 1 yes 3 I'm trying to reformat this on another worksheet into a table that looks like: id 1 2 3 1 yes no yes I'm using this vlookup: =VLOOKUP(A2,sheet2!\$F\$1:\$G\$10,2,FALSE) where a2...

## Deconstruct Excel Formula To Get Result Without Trying Values

excel,formula
I need to deconstruct Excel formulas so that I don't have to put values in to see what the result is. I want to put in a result and get a values. I know this is difficult given with multiple variables the answer could be different. I'm looking for more...

## Referencing a new inserted column Excel VBA

excel,vba,excel-vba
I am trying to reference a cell in the below formulaes. 'AUA Summary'!\$D\$9 . Each time the macro runs a new column D is inserted. The Problem: When the column is inserted my reference moves to ** 'AUA Summary'!\$E\$9. How do I get to reference 'AUA Summary'!\$D\$9 even if a...

## Formatting specific part of text string in VBA

excel,vba,excel-vba,outlook,format
I am in process of creating a macro that will save the current workbook, create a new outlook message and attach the file to the message. My macro does that but I can not format the text in the body of the email to my liking. Dim OutApp As Object...

## Sort multiple columns of Excel in VBA given the top-left and lowest-right cell

excel,vba,excel-vba,sorting
I am trying to sort these three columns (Sort By Col-2) in excel using VBA. Top-left (Row number and Column number e.g. 1,1) and lowest-right cell (Row number and Column number e.g. 9,3) are known. Every cell contains the values of String type. Input: Col-1 Col-2 Col-3 P1 I1 XYZ...

## Using VLOOKUP formula or other function to compare two columns

mysql,excel,vba,date
I have one table like this: SHORT TERM BORROWING 1/6/2009 94304 12/31/2010 177823 6/30/2011 84188 12/31/2011 232144 6/30/2012 94467 9/30/2012 91445 12/31/2012 128523 3/31/2013 83731 6/30/2013 78330 9/30/2013 70936 12/31/2013 104020 3/31/2014 62345 6/30/2014 62167 9/30/2014 63494 12/31/2014 104239 3/31/2015 69056 I have another column which lists each date from...

## VBA “Compile Error: Statement invalid outside Type Block”

excel,vba,excel-vba,excel-2010
I am running a VBA Macro in Excel 2010 with tons of calculations, so data types are very important, to keep macro execution time as low as possible. My optimization idea is to let the user pick what data type all numbers will be declared as (while pointing out the...

## Copying sheet to last row of a sheet from another workbook

excel,vba,excel-vba
I'm stuck in this block of code that copies sheet("Newly Distributed") to the last row of sheet("Source") from another workbook. The error is runtime error 9. What's wrong with my code? Any response would be appreciated. Private Sub copylog3() Dim lRow As Long Dim NextRow As Long, a As Long...

## EXCEL VBA: How to manupulate next cell's (same row) value if cell.value=“WORD” in a range

excel,vba,excel-vba
I want to change the next cell in same row in a if cell.value="word" in a range. I have defined the range, using 'for' loop. In my code, if cell.value="FOUND THE CELL" then cell.value+1="changed the next right side cell" cell.value+2="changed the second right side cell" end if I know this...

## Range, Select, Change contents, Allignment or Offset?

excel,vba,excel-vba
I have a case at the moment where I am moving down the column with the names below and clicking on a macro, that then marks the indicator with a 35, a few columns down to the right. Due to the nature of the page, I am wanting to count...

## Excel VBA Loop Delete row does not start with something

excel,excel-vba
I have some data at work looks like this: 00 some data here... 00 some data here... 00 some data here... 00 some data here... Other data I want to remove Other data I want to remove Other data I want to remove Other data I want to remove 00I...

## Excel - select a cell based on adjacent cell value

excel
I have the following excel spreadsheet and I am trying to work out how I can write a formula in order to provide the values in column D. In each row, there is a test date, I am trying to calculate the day difference from each test date to the...

## How do I get a cell's position within a range?

excel,vba,excel-vba
How would I go about getting the relative position of a cell within a range? Finding the position of a cell in a worksheet is trivial, using the Row- and Column-properties, but I am unsure of how to do the same within a range. I considered using the position of...

## Disaggregate one row of data to multiple rows

Goodafternoon! I am having some trouble with my dataset. I am using a Google AdWords export for data analysis and I want to fit a logit regression model to the data to determine whether an experiment I have conducted impacts the conversion. The problem is that the data is aggregated...

## Interface Controls for DoEvent in Excel

excel,vba,excel-vba,loops,doevents
I have a macro to loop through a range and return emails to .Display based on the DoEvents element within my module. I iterate that: row_number = 1 'And Do DoEvents row_number = row_number +1 'Then a bunch of formatting requirements Loop Until row_number = 'some value I am wondering...

## Using a cell's number to insert that many rows (with that row's data)

excel,excel-vba
I have data in excel that looks like this {name} {price} {quantity} joe // 4.99 // 1 lisa // 2.99 // 3 jose // 6.99 // 1 Would it be hard to make a macro that will take the quantity value ("lisa // 3.99 // 3") and add that many...

## Return #N/A error from ExcelDNA

excel,visual-studio-2010,excel-dna
I'm pretty new to excelDNA, so I may be missing something obvious. I'm trying to return a #N/A from an excelDNA UDF. The function I'm using (via Visual Studio 2010) is below: public static object returnError() { return ExcelDna.Integration.ExcelError.ExcelErrorNA; } When called from an Excel worksheet, this returns a #VALUE...