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

Excel - select a cell based on adjacent cell value


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:

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:



Deconstruct Excel Formula To Get Result Without Trying Values

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...

Ordering values from random list in 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...

Dates not recognized as Dates, despite format

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...

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...

Label linked to a text box value

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...

Excel - select a cell based on adjacent cell value

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 do to count rows in a sheets with filters? With a suppress lines

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....

VBA - .find printing wrong value

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...

Interface Controls for DoEvent in Excel

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)

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...

Excel VBA Loop Delete row does not start with something

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 Search VBA macro

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...

Using a stored integer as a cell 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 +...

VBA - Unable to pass value from Private to Public Sub

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...

Range, Select, Change contents, Allignment or Offset?

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...

How to write formula for cell in 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...

Converting column from military time to standard time

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...

excel search engine using vba and filters?

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...

C# code to add hyper link in excel sheet

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...

timestamp SQL to 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...

if condition inside Insert query in 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 &...

Using VLOOKUP formula or other function to compare two columns

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...

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...

Formatting specific part of text string in VBA

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...

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

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...

Return #N/A error from ExcelDNA

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...

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

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...

Copying sheet to last row of a sheet from another workbook

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...

12 Characters Including leading and following zeros

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...

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

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...

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

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...

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

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...

Finding position of a particular string containing cell in Excel

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...

Comparing cell contents against string in Excel

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...

If statement and addition

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?

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...

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

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...

Identifying cell in 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...

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

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...

Errors 91 and 424 when iterating over ranges in Excel VBA

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 2013 Add a Connector Between Arbitrary Points on Two Different Groups

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...

How to convert excel data to json at frontend side

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...

Referencing a new inserted column 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...

Excel vlookup expansion

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...

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

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...

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

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...

VBA “Compile Error: Statement invalid outside Type Block”

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...

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

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...

adding variables into another variable 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...