Can you assign index values to .Currentpage VBA/Excel? - excel

I'm trying to create a Macro that will, among other things, set the .CurrentPage to a specific value. My question is can you use an index value instead of the name of one of the values?
ActiveSheet.PivotTables("PivotTable1").PivotFields("starttime").CurrentPage = "11/19/2018"
Here is an example line that I'm using. The problem is the dates will change every week to represent the new data. However there will always be five options, Monday to Friday. So instead of having to use the date, which I'll have to change every week, can I use an index value instead?
I.e. [0] for Monday and [4] for Friday etc. If this is possible then what is the correct syntax for this? I've looked all over the web and found nothing even remotely related to using index numbers instead of values.

If you know that your field will only contain the relevant items and nothing else, then:
With ActiveSheet.PivotTables("PivotTable1").PivotFields("starttime")
.CurrentPage = .PivotItems(3).Value
End With
However pivot tables may retain items deleted from the data source. If that is how it is set up for you, then you will either need to remove cached items before using this code, or calculate that page value instead of looking it up in the list of available values, which should be not difficult given that it is based on the current week.

Something like this
Public arrDate(4) As Date
Sub CreateDateArray()
Dim i As Integer
For i = 0 To 4
arrDate(i) = DateAdd("d", -Weekday(Date, vbMonday) + (i + 1), Date)
Next i
End Sub
or something like this
Function DateFromIndex(intDay As Integer) As Date
DateFromIndex = DateAdd("d", -Weekday(Date, vbMonday) + (intDay+1), Date)
End Function

Related

Why is midnight added to my array instead of the date?

I declare a date array as such:
Dim date_array() as Date
It's goal is to store dates found in a range.
Dim date_range As String
I declare it as a string because I have an input form where a user specifies the range of dates (e.g. A1:A5).
Then I calculate how many cells are in the range and specify the size of the date_array.
ReDim date_array(Range(date_range).Cells.count)
So far so good. I then loop through each element of date_array and add the date from the range.
Dim i As Long
i = 0
For Each r In ThisWorkbook.Worksheets("Name").Range(date_range)
date_array(i) = r.Value
i + i + 1
Next r
However, when I do a MsgBox(date_array(i)) during this loop, I get a value of 12:00:00 AM instead of the date I want (e.g. 2/2/2019) which tells me something is getting lost in translation.
I get the correct result if I do MsgBox(r.Value)... so it seems like something about the way I'm assigning the date to the array is wrong.
Has anyone run into an issue like this before? How can I fix it?
The larger goal is to map data between two files using date + a naming convention as a validation, so I need the array to store the correct date in a date format so it can be compared to a different cell value later.
Thank you,

Returning multiple values using Vlookup in excel

I have an excel sheet set up to automatically calculate meetings per day by day of the week. I would like to write a formula to return all dates I have a meeting scheduled (comma separated preferably), but I am having some difficulty. Using Vlookup, I can only get it to return the first date.
For example, here is what my data looks like:
A B C
Initial Meetings Follow-up Meetings Date
1 1 7/29/2015
0 1 7/30/2015
1 1 7/31/2015
0 0 8/1/2015
0 0 8/2/2015
I would like to write a formula to return "7/29/2015, 7/31/2015" in one cell, and "7/29/2015, 7/30/2015, 7/31/2015" in another, but I seem to be stuck.
You can't do this with vLookup.
This can be done relatively easily in a VB script, but it would affect portability as many if not most users disable macros by default and in many cases users are prevented from using Macros because their company disables them and makes it policy that users should not use them.
If you are OK with Macros, you can put the following into a new module and then use =MultiVlookup(lookup_value,table_array, col_index_num) in the same way as you'd use vlookup and it should give you a comma separated list of multiple matches:
Public Function MultiVlookup(find_value, search_range, return_row)
Dim myval ' String to represent return value (comma-separated list)
Dim comma ' Bool to represent whether we need to prefix the next result with ", "
comma = False
'Debug.Print find_value.value, return_row
For Each rw In search_range.Rows ' Iterate through each row in the range
If rw.Cells(1, 1).value = find_value Then ' If we have found the lookup value...
If comma Then ' Add a comma if it's not the first value we're adding to the list
myval = myval + ", "
Else
comma = True
End If
myval = myval + Str(rw.Cells(1, return_row).value)
End If
Next
MultiVlookup = myval
End Function
This may not be the cleanest way of doing it, and it isn't a direct copy of vlookup (for instance it does not have a fourth "range lookup" argument as vlookup does), but it works for my test:
Finally my original suggestion (in case it helps others - it's not the exact solution to the question) was:
I've not tried it myself, but this link shows what I think you might be looking for.
Great code, but don't forget to add the following is you use Option Explicit:
Dim rw As Range
WHEELS

Turning an excel formula into a VBA function

I'm a bit new to trying to program and originally was just trying to improve a spreadsheet but it's gone beyond using a basic function in excel. I have a table that I am having a function look at to find a building number in the first column and then look at start and finish dates in two other respective columns to find out if it should populate specific blocks on a calendar worksheet. The problem occurs because the same building number may appear multiple times with different dates and I need to to find an entry that matches the correct dates.
I was able to create a working though complicated formula to find the first instance and learned I can add a nested if of that formula again in the false statement with a slight change. I can continue doing that but it becomes very large and cumbersome. I'm trying to find a way to make a function for the formula with a variable in it that would look at how many times the it has already been used so it keeps searching down the table for an answer that fits the parameters.
This is currently my formula:
=IFERROR(IF(AND(DATE('IF SHEET (2)'!$F$7,MATCH('IF SHEET (2)'!$C$2,'IF SHEET (2)'!$C$2:'IF SHEET (2)'!$N$2,0),'IF SHEET (2)'!C$4)>=VLOOKUP("2D11"&1,A2:F6,4,0),DATE('IF SHEET (2)'!$F$7,MATCH('IF SHEET (2)'!$C$2,'IF SHEET (2)'!$C$2:'IF SHEET (2)'!$N$2,0),'IF SHEET (2)'!C$4)<=VLOOKUP("2D11"&1,A2:F6,4,0)),IF(VLOOKUP("2D11"&1,A2:F6,3,0)="2D11",VLOOKUP("2D11"&1,A2:F6,6,FALSE)),"NO ANSWER"),"ERROR")
Where you see 2D11&1 is where I need the variable for 1 so it would be "number of times it's been used in the function +1" then I could just loop it so it would keep checking till it ran out of 2D11's or found one that matched. I haven't posted before and I'm doing this through a lot of trial and error so if you need more info please post and say so and I'll try to provide it.
So rather than have someone try to make sense of the rediculous formula I posted I though I would try to make it simpler by just stating what I need to accomplish and trying to see how to turn that into a VBA function. So I'm kinda looking at a few steps:
Matches first instance of building name in column A with
building name for the row of the output cell.
Is date connected with the output cell >= start date of first entry(which is user entered in column D).
Is date connected with the output cell <= end date of first entry(which is user entered in column E).
Enters Unit name(located in column F) for first instance of the building if Parts 1, 2, and 3 are all True.
If parts 1, 2, or 3 are False then loops to look at next instance of the building name down column 1.
Hopefully this makes things clearer than the formula so I'm able to get help as I'm still pretty stuck due to low knowledge of VBA.
Here is a simple solution...
Building_name = ???
Date = ???
Last_Row = Range("A65536").End(xlUp).Row
For i = 1 To Last_Row
if cells(i,1).value = Building_Name Then
if date >= cells(i,4).value Then
if date <= cells(i,5).value Then
first instance = cells(i,6).value
end if
end if
end if
next
you should add a test at the end to avoid the case where there is no first instance in the table
If I understand correctly, you have a Table T1 made of 3 columns: T1.building, T1.start date, T1.end date.
Then you have 3 parameters: P1=building, P2=start date, P3=end date.
You need to find the first entry in table T1 that "fits" within the input parameters dates, that is:
P1=T1.building
P2<=T1.start date
P3>=T1.end date
If so, you can define a custom function like this
Public Function MyLookup(Key As Variant, DateMin As Variant, DateMax As Variant, LookUpTable As Range, ResultColumn As Integer) As Range
Dim iIndx As Integer
Dim KeyValue As Variant
Dim Found As Boolean
On Error GoTo ErrHandler
Found = False
iIndx = 1
Do While (Not Found) And (iIndx <= LookUpTable.Rows.Count)
KeyValue = LookUpTable.Cells(iIndx, 1)
If (KeyValue = Key) And _
(DateMin <= LookUpTable.Cells(iIndx, 2)) And _
(DateMax >= LookUpTable.Cells(iIndx, 3)) Then
Set MyLookup = LookUpTable.Cells(iIndx, ResultColumn)
Found = True
End If
iIndx = iIndx + 1
Loop
Exit Function
ErrHandler:
MsgBox "Error in MyLookup: " & Err.Description
End Function
That may not be the most performant piece of code in the world, but I think it's explanatory.
You can download this working example

Lotus Notes: Displaying days of a month, following the weekdays of it

I have a not so nice question. I've been thinking about this for like a month now and read a couple of books but can seem to find an answer or how to execute this. As you all know, I'm making this application that generates date. I have one combobox it has months in it, starting january to december, two column table, first colum displays the day and the second one displays the weekdays, on selecting month combobox, it must display the days in that month on first column and weekdays on 2nd column, by row. example: I choose january, on the first column it will display the days of that month, 1st row is 1, 2nd row is 2, and so on, and same as weekdays. I'm kinda new to LN. Can you give me an idea for it? Hope you can help me out.
This is a solution based on Notes #Formula. Only a few lines of code are necessary to achieve the result.
First we need the form
The formula for Days is
_days :=1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:28:29:30:31;
_numberDays := #Day(#Adjust(#Adjust(#Date(#ToNumber(Year); #ToNumber(Month); 1); 0; 1; 0; 0; 0; 0); 0; 0; -1; 0; 0; 0));
#Subset(_days; _numberDays)
and the formula for Weekday is
_weekdays := #Transform( #ToNumber(Days); "day";
#Weekday(#Date(#ToNumber(Year); #ToNumber(Month); day)));
#Replace(#Text(_weekdays);
"1":"2":"3":"4":"5":"6":"7";
"Sunday":"Monday":"Tuesday":"Wednesday":"Thursday":"Friday":"Saturday")
That's it.
The fields Month and Year have to have the property "Refresh fields on keyword change".
The fields Days and Weekday need "Computed for display", "Allow multiple values" and "New Line" as separate values.
The result will look like this
Truly dynamic tables are difficult. In this case it's definitely possible because you have a defined number of rows, but it's still somewhat messy.
I'm not aware of anything built in that will easily tell you how many days there are in each month. I'd probably just create a config doc with year, month, and numberOfDays fields, and hidden view that you can use for lookups. You're going to need this in many places, and you don't want to do the lookup each time, so do it in a hidden computed field that comes after your dropdown but before your table. (Be sure to set properties so the field is recomputed after the value in the dropdown is changed.) Call the field something like daysInSelectedMonth.
Obviously the first column is easy: just create your table and enter the numbers 1 through 31, and apply a hide-when formula to the cells for rows 29 through 31 so that they only show up if daysInSelectedMonth is the right number of days. You don't need the hide when in the other rows.
For the second column, you will need to use computed for display fields. I would strongly suggest naming them something like weekday_1, weekday_2,... weekday_31 so that you can use #ThisName and some simple string manipulation to extract the number from the field name. That will tell you what row the formula is in, and it is your day number. The benefit of doing it this way is that your formula can be exactly the same in every one of the fields -- just a cut-and-paste into the other fields after you get it right once.
I would suggest starting to work on the formula in the weekday_31 field, and when you get it right (showing the correct weekday in a month that does have 31 days, and blank in a month that does not), then you can copy the formula to the rest of the fields. You will need to use an #If to detect whether the month has the correct number of days -- this is easy, except for leap year. I'm going to leave that part up to you. Just make it return "" if the month does not have the right number of days, and then have the final clause of the #f use #Date to build the value for the date that you are working on and then use the #Weekday function to display the value.
It all depends on a few things:
Web application or Notes client application?
What is the end result of the exercise, i.e. what is the table intended to be used for? Display purposes only?
Making some assumptions (Notes client application, and table used only for display), I see two ways to do this.
An easy way to do this is to create the table with 31 rows and 2 columns.
In the cells you create fields: Day1, Weekday1, Day2, Weekday2, etc.
You also need a year field, unless it is always current year.
Set a hide-when formula on rows 29-31, to hide if the Day field for that row is blank.
On the advanced properties tab for the combobox where you select month, set "Run Exiting/OnChange events after value change".
In the Exiting event for the combobox, write some Lotusscript that populate the fields with days and weekdays, based on selected year and month. Something like this (untested:
Sub Exiting(Source As Field)
Dim session As New NotesSession
Dim ws As New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Dim monthName As String
Dim YYYY As String
Dim firstDate As NotesDateTime
Dim lastDate As NotesDateTime
Dim n As Double
Dim i As Integer
Dim dayname(1 To 7) As String
dayname(1) = "Sunday"
dayname(2) = "Monday"
dayname(3) = "Tuesday"
dayname(4) = "Wednesday"
dayname(5) = "Thursday"
dayname(6) = "Friday"
dayname(7) = "Saturday"
Set uidoc = ws.CurrentDocument
YYYY = uidoc.FieldGetText("Year")
monthName = uidoc.FieldGetText("Month")
Set firstDate = New NotesDateTime("1 " & monthName & ", " & YYYY)
Set lastDate = New NotesDateTime(firstDate.DateOnly)
Call lastDate.AdjustMonth(1)
Call lastDate.AdjustDay(-1)
i = 0
For n = Cdbl(firstDate.LSLocalTime) To Cdbl(lastDate.LSLocalTime)
i = i + 1
Call uidoc.FieldSetText("Day" & i, Cstr(i))
Call uidoc.FieldSetText("Weekday" & i, dayname(Weekday(Cdat(n))))
Next
Call uidoc.Refresh()
End Sub
Another way to create a truly dynamic table, is the method I blogged about here:
http://blog.texasswede.com/dynamic-tables-in-classic-notes/
The benefit is that it is more flexible, and you can create a nicer layout without needing to create a large number of fields.

Dates and Charting

I have three sets of data and each has two columns.
The first column is Date and second column is Price. The dates are formatted different with each data set eg. Gold's date(1951), Money Supply M2's date (1951-01), and Money Sup. M3 Date (9/01/1951)
What i need:
I want to chart these with dates on x-axis and price on y-axis
Questions:
do i need to make Gold's Date(YYYY) and Money Supply M2's Date(YYYY-MM) a date object?
if so how?
do i need to place all dates in one column and create a sub to help sort the Price with appropriate Date?
Does this make sense?
I have very little experience programming in VBA and was having a hard time finding info on using dates. I came across an Answer, given by the person who edited this (brettdj), that listed a few extremely helpful sights on VBA programming for excel. One of those had info on the DateSerial() function. I was then able to throw together some code to quickly fix my problem.
Sub CreateDates()
Dim dt As Date
Dim s As String
For Each c In Worksheets("Sheet1").Range("A7:A27080").Cells
s = Len(c.Value)
If s = 4 Then '(YYYY)
dt = DateSerial(s, 7, 1)
c.Value = dt
End If
If s = 7 Then '(YYYY-MM)
y = Left(s, 4)
m = Right(s, 2)
dt = DateSerial(y, m, 1)
c.Value = dt
End If
Next c
End Sub
I could probably spend some time and add some regular expressions and make a one-size fits most, but this will work as i want have to use it very often.

Resources