VBA Function able to search through cells? - vba

Back Story
At my job we use a desk calendar to keep track of a multitude of random details that occur: Everyone's daily hours, what type and how many reports were sent, etc. To help us in filling out a few forms my boss decided he wanted to create a spreadsheet for the month and keep it as up-to-date as possible day by day. He went on vacation before this month started, so I've been taking over his duties. Something I noticed is that he hardwired the calculations for the totals (everyone's total hours, total reports sent, etc), so that when I changed the dates from January to February we had some left over ones that lead into March. I deleted them and then the formulas all threw #REF! errors because of it.
How the data is set up is simple:
AB 2.50
CD 3.50
EF 8.00
...ETC...
With the AB,CD,EF being in one column, and the values being in the adjacent column.
The Question
I tried to get this to work, with no luck, so I'm thinking it might be impossible but I thought I'd ask a group of people who know more about the subject than I do: in a function I made I have it accept a string parameter to search for, if it finds it, it moves to the adjacent cell and adds that value to the running total. It then returns that number at the end, so a call to this function would resemble
=getTotals("AB") ' this would display whatever the total for AB is
But when I tried this all I got was a #VALUE! error in the cell.
Is there any way I can get this to work the way I want it to, without the use of a full macro?
The Function
I got this function to work, how I wanted to
Function getTotal(rng As Range, search As String) As Double
Dim r As Range
getTotal = 0
For Each r In rng
If r.Value = search Then
getTotal = getTotal + r.Offset(0, 1).Value
End If
Next
End Function
Calling it like so: =getTotal(A1:D2, "AD")

SUMIF should get you what you need:
=SUMIF(A1:A10,"AB",B1:B10)
Assuming your 'AB' values are in column A, rows 1-10 and the number values are in column B, rows 1-10.
The first argument in SUMIF is the range to check, the second argument is the condition that must be met (search criteria), and the 3rd [optional] argument is the corresponding range from which to get the values to be summed.

Related

Insert text in cells when above cell meets condition

I have a schedule sheet for the whole year for a group.
The third row has all the dates of the year, the next couple of rows has the name of each group member.
Members specified in A4:A9.
Holidays are specified in cells A20:A28.
So, what I want to do, probably through VBA, is to make a rule like with conditional formatting, that inserts the word "Holiday" in B4:B9 if B3 matches a date in A$20:A$28, and then into C4:C9 if C3 matches and so on.
Now I cannot write this condition in every cell since it's a schedule used by every member, which is the suggestion I often got from googling, and I can't do it with conditional formatting, so I'm guessing VBA is the way to go, but the VBA code I've found so far seems to use specific cells and wouldn't go through each column.
Without questioning your general approach, a simple code that does what you plan to do could work like the following:
Option Explicit
Sub markhd()
' get calendardays, holidays and employees somehow into collections
' that can be looped. Since that information is stored in a worksheet,
' using ranges is one way to achive that
' holidays
Dim rhd As Range
Set rhd = ActiveSheet.Range("A20:A28")
' group employees
Dim remp As Range
Set remp = ActiveSheet.Range("A4:A9")
' calendar days
Dim rcal As Range
Set rcal = ActiveSheet.Range("B3:NB3")
Dim c As Object
' Loop every day (every c-object in your calendar days),
' then write "Holiday", if it matches an entry in your holiday-range
For Each c In rcal
If Not IsError(Application.Match(c, rhd.Cells, False)) Then
remp.Offset(0, c.Column - remp.Column).Value = "Holiday"
End If
Next c
End Sub
Note:
The concept #EganWolf mentioned is to look for similar objects (calendar days in this example) and iterate through them, performing an action (writing "Holiday") if a check is passed (calendarday is in the range of holidays). There is a gazillion of different ways implement this, i merely posted one easy to follow example
Looping each and every calendar day we're doing 365 iterations here, attempting to match each calendarday in the 9 holidays.
However, we could do this the other way around: loop the 9 holidays, match them in the 365 calendar days, therefore looping only 9 times. Performance could theoretically swing both ways, since despite having less iterations, a single iteration could take longer... but, obviously, at 365 days performance is merely a theoretical problem.
Hope that helps!

Dynamic reference in excel formula

I have the following array formula which works for what I want to do but I'm trying to change the formula when a user selects a value.
=INDEX($A$2:$B$70,SMALL(IF($A$2:$B$70=$A$121,ROW($A$2:$B$70)),ROW(1:1))-1,1)
It's used for a monthly report and the user will choose from a drop down the day of the month, e.g 1,2,3 - 31.
So if the user selects 1 from the drop down menu I want the formula to use the above formula.
If they select 2 for example I want the formula to move over a column so it would change to
=INDEX($A$2:$C$70,SMALL(IF($A$2:$C$70=$A$121,ROW($A$2:$C$70)),ROW(1:1))-1,1)
and so on moving over a column at a time.
It this possible at all or can it even be done without VBA?
I have an example of what I want done on the following link
https://docs.google.com/spreadsheets/d/1MDOzoQxYLgW-UOyljZsMwSu8zyAB7O2k1V-bTNP5_F0/edit?usp=sharing
All the data is on the first tab called staff. Each employee has a row and the duty assigned under the corresponding day column.
On the Roster tab it summarises each day. So what I am trying to get to happen is when you choose the day of the month (or preferably the actual date) the sheet changes to reflect the data.
At the moment the code I have working does for just Day 1 because the column references are coded into the formula. I was hoping to somehow choose 6 for example from the drop down and then the formula will map chosen day to the corresponding range in the raw data and update the formula and change the formula from Staff!$A$2:$B$68 to Staff!$A$2:$G$68.
If the formula finds no more entries if shows #NUM! but I intended to use the function ISERROR() to replace #NUM! with "".
This is what I'm trying to achieve it if makes sense?
There are a few issues here/ You are returning the value from column A so the first range can be $A$2:$A$70 and that means you don't need the 1 to specify the column_num. The IF statement was covering A2:C70 when you really only want either B2:70 or C2:C70 depending on the 1 or 2.
Assuming that A122 has either a 1 or 2 in it then,
=INDEX($A$2:$A$70, SMALL(IF(INDEX($B$2:$C$70, 0, $A$122) = $A$121, ROW($1:$69)), ROW(1:1)))
Standard non-array alternative,
=INDEX($A$2:$A$70, SMALL(INDEX(ROW($1:$69)+(INDEX($B$2:$C$70, 0, $A$122) <> $A$121)*1E+99,, ), ROW(1:1)))

Sumproduct dates

I have a spreadsheet worksheet called “ISO Procedure Master List” where the date a procedure is requested is in column G (Format m/dd/yyyy).
In column H the date the procedure is completed is entered. Column H uses the same date format but may contain blanks (procedure not completed yet).
There are currently 67 rows of information in the spreadsheet that span from 2011 to 2015 and that number will continue to grow.
QUESTION, I would like to get the average time (in days) it took from a procedure request (column G) to the completion of procedure (column H) for all of the procedures requested in a given year.
In other words the average (in days) time it took to complete procedures in a given year.
This answer will be in a cell C34 in the same workbook but a different worksheet called “ISO Matrix”. (This information probably does not matter but I thought I would add I just in case)
I have tried several Sumproduct variations with no success.
Assumptions:
Dates in columns G and H are dates, not text string,
Data start in row 2, using row 1 for headings.
For convenience, I assume you have named the ranges you wish to average requestDate and completeDate
You wish do ommit the rows where the procedure is not finished from the average calculation.
After naming your ranges, input the following formula into C34 on "ISO Matrix" tab:
=AVERAGE(IF(completeDate<>"";completeDate-requestDate))
This is an array formula, so when normally pressing enter, remember to press CTRL+SHIFT+ENTER instead. When highlighting the cell, it will then look like this:
{=AVERAGE(IF(completeDate<>"";completeDate-requestDate))}
NOTE: My language pack uses ; as formula separator, so if you language uses , instead, change the formula to:
=AVERAGE(IF(completeDate<>"",completeDate-requestDate))
EDIT: So, I didn't catch that you needed to average by year. In line with my recent formula, it could be update to suit your request.
=AVERAGE(IF(completeDate<>"";IF(YEAR(requestDate)=A15;completeDate-requestDate)))
where A15 holds the year you are interested in. I tried it with an AND in the first IF instead of two IFs, but that did not seem to work. Mind you, you might still need to change ; to , and you also need CTRL+SHIFT+ENTER for this one.
You could also add the code below, to handle the case where you test a year that is not present in the list:
=IFERROR(AVERAGE(IF(completeDate<>"";IF(YEAR(requestDate)=A15;completeDate-requestDate)));"No such year")
...or something like that

Find Last Row of Name with constantly changing names

I'm really stuck on this one. I have a spreadsheet with thousands of rows. I use this code to filter them based off of product in the E column.
Sub IsolateCCENCE()
Dim Operations As Workbook
Dim Operations_Sheet As Worksheet
Set Operations = Workbooks("Operations for Macros")
Set Operations_Sheet = Operations.Worksheets("Operations")
Operations_Sheet.Range("$A$6:$AH$13108").AutoFilter Field:=5, Criteria1:="=CCE" _
, Operator:=xlOr, Criteria2:="=NCE"
End Sub
Which works and leaves me with just under 1700 rows. Within these rows, in the A column, there are company names. Each company takes up approximately 20 rows. Each row represents a payment and has a corresponding date, in the D column. I need a macro (I'm assuming with a loop) that will then do the following:
Go through the rows, find the last row for each company
In that row, find the corresponding date
If that date is within 30 days from today, generate an email
Part 3 is easy. But Part 1 and 2 I can't seem to get. The data is always going to be changing.
Maybe it would be easier to have all of the data copy and pasted into another spreadsheet and then filter through every single company, find the last row (and thus the corresponding date)? But I don't know I would have a macro defined to filter through each company when the company names will be changing constantly.
I appreciate any help. Thanks in advance!
If a specific company name in say F1 then:
=MIN(IF(A:A=F1,D:D))
entered with Ctrl+Shift+Enter should give you the earliest date for the company named in F1, that if more recent than today()-30 (or less far into the future than today()+30 ?) you might use for your e-mail trigger (subject to other filtering etc).

Excel Formula to calculate number of user hits in a system everyday

This is the continuation of my previous questions and I have included my global aim with project.
Excel Link:
https://drive.google.com/file/d/0B5W4CgZKsARFSmhqV0ZSM1lBSkE/view?usp=sharing
Task:
The task is to collect the "number hits" of a user in an application "on each day". I can collect a log from the system which will give me the name of the users and their last hit date and total number of hits.(This total number of hits in not on daily basis, but sum of all days). and I need to make a formula to segregate these on daily basis
Screenshot:
To understand in better way I have created few screenshot, which I am looking to implement.
The excel has two tabs raw_data and value_capture. I will use raw_data to paste my raw data collecting from system log and value_capture to generate day by day hit statistics
Raw_data tab:
It has three details, 1. date. 2. name and 3 totals hits(This total hits are overall hits of that user on all days)
value_capture:
This has all user names and all dates to mark each day and a column to display all hits.
Now, considering an example of date 20141120, all users hits are 0.
raw_data shows 0 against all users
so value_capture are has to be updated with same
Now on next day 20141121, there is some hits against some users. (Note : if there is no hit against a user, it will only the previous date ie,date will update only if there is a hit on that day)
value_capture updated with that details
On 20141122, there are some more hits against the users
value_capture updated with the details. since the raw_data will show total number of hits against a user, the way of calculating on a particular will be total hits- previous date hit
I am stuck at a way to develop the excel formula here.Looking for an idea to implement this.
Note :
Users name will be fixed on both tabs, but that may come in different order in raw_data tab.
UPDATE
My raw_data sheet will be updated everyday and I want my formula results be fixed in the value_capture sheet after the values are updated (removed) from sheet raw_data
So as i mentioned in my answer to your previous question, the only way to save the results of a formula after deleting/removing its reference cells, is to use a macro.
First of all
you need a proper formula to pull the data from the raw_data sheet and then calculate the difference between that particular cell where the formula resides and the sum of previous cells in that row.
we need two formulas:one for the column B of your value_capture sheet. and the second one for the rest of your table. why? because in the first column you don't calculate the difference between itself and the previous cells, because there aren't any. So there is a little difference in the formula.
FORMULA ONE:(paste in B3 and drag and fill down)
=SUMIFS(raw_data!$C:$C;raw_data!$B:$B;$A3;raw_data!$A:$A;B$2)
FORMULA TWO:(paste in C3 and drag and fill down and to the right)
=IF(SUMIFS(raw_data!$C:$C;raw_data!$B:$B;$A3;raw_data!$A:$A;C$2)-IF(ISNUMBER(B3);SUM($B3:B3);0)>0;SUMIFS(raw_data!$C:$C;raw_data!$B:$B;$A3;raw_data!$A:$A;C$2)-IF(ISNUMBER(B3);SUM($B3:B3);0);0)
As you see in my screenshot for user in cell A3, we have value of 4 for the date 20141120 and the next day the value is 14 but the cell gets the difference, that is 10, and then then next day, the value increases to 16, so the cell value for D3 becomes 2 which is the different of 16 for that day and the sum of previous ones. This continues until today's value which is 24 so the cell gets 7 because the sum of previous ones is 17.
Now that you have your values captured correctly, with respect to the difference with the sum of previous days, it is time to make them fixed and eternal.
For this you need a macro:
Sub saveMyData()
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Range("B3:L18").Copy
ws.Range("B3").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
End Sub
So obviously you need to update this range "B3:L18" this is what I have in the example sheet only.
Now this macro, copies and pastes all the values from that range onto itself, so you lose your formulas.So each day, you need to go to *line 21** of the same sheet and get the formula from C21 and paste it on somewhere on row 3 from where you want to continue capturing the new day's data. (you won't need the first formula, because it is only used once in the first column, the first day.)
This was the only way to capture the values using formulas and then save the results of the formulas in their place and go and fetch new data. I couldn't think of any other strategy to make it more automatic, except for writing mova VBA and letting excel go and find where you left the day before and paste the formulas in their right place and repeat the task.
all these formulas are array formulas, so press ctrl+shift+enter to calculate the formulas.
Remember to adjust the formulas to your regional settings, i suppose, by replacing the ";" with ",".
here is the example sheet downloadable from this link
Tell me if you have problems anywhere and don't forget to answer my question in the comments about the way you update your dates in row 2 of value_capture.
The formula that you are looking for is SUMIFS
=SUMIFS([SUM RANGE],[RANGE 1],[VALUE 1],[RANGE 2],[VALUE 2])
SUM RANGE is the column of values that you want to SUM so that is your column C. For Range 1 you want to select the range of IDs. The VALUE 1 will be equal to the value in Column A Row X. For RANGE 2 it will be the Date column. For VALUE 2 it will be the value in the column header.
Put this together and you have something akin to:
=SUMIFS(raw_data!$C:$C,raw_data!$B:$B,$A3,raw_data!$A:$A,B$2)
This would be in cell B3 and you could fill the other cells from there.
If total hits for a day is a rolling count of ALL hits ever then at the end of your equation you need to subtract the sum of the prior days.
For example:
=SUM(B3:B4)
This would only need to be added to subsequent columns (not the first).
So the equation in C3 would be
=SUMIFS(raw_data!$C:$C,raw_data!$B:$B,$A3,raw_data!$A:$A,C$2)-SUM(B$3:C3)
Then in D3 it becomes
=SUMIFS(raw_data!$C:$C,raw_data!$B:$B,$A3,raw_data!$A:$A,D$2)-SUM(B$3:D3)
Try Sumifs formula
=SUMIFS(raw_data!$C:$C,raw_data!$B:$B,$A3,raw_data!$A:$A,B$2)-IF(ISNUMBER(A3),A3,0)