VBA Dates

mmetzinger

Board Regular
Joined
Dec 30, 2010
Messages
61
Ok, I am trying to create a custom variable with data pulled from other variables but I can't get excel to accept it. I keep getting a type mismatch but can't figure out how to get past it

Code:
Public StartDate As Date
StartDate = "11/1/2010"

Dim Month As String
Month = DatePart("M", StartDate)

Dim Year As String
Year = DatePart("YYYY", StartDate)

Dim MonthYear As Date
MonthYear = Month & "/" & "*" & "/" & Year

Can anyone tell me how to combine the found month and year into the new variable? Is there any easier way to get the date without a value in the day field?
 

Excel Facts

Easy bullets in Excel
If you have a numeric keypad, press Alt+7 on numeric keypad to type a bullet in Excel.
What you've done is create a String that looks like this:

"11/*/2010"

Since this doesn't represent a valid date, you cannot assign this String to a Date-type variable.
 
Upvote 0
I figured that much I just need to figure out how to generate a date that has no day value because I need to be able to search a sheet for the last row that has data for that month.
 
Upvote 0
If you set the date to the last day of the month, then lookup functions would find the largest value <= that date, if the data is sorted ascending by date.
 
Upvote 0
Why do you need VBA? This can be done with a formula:

With desired month in H1 and desired year in I1:

Excel Workbook
ABCDEFGHI
1112010
211/1/200912
311/3/20091530
411/4/201027
511/16/201030
612/1/2010
Sheet1
 
Upvote 0
using your variables, something like

Code:
monthyear = DateSerial(Year(startdate), Month(startdate) + 1, 0)
 
Upvote 0
Using those variables, Startdate should be entered as a date literal not a string:
Code:
StartDate = #11/1/2010#
 
Upvote 0

Forum statistics

Threads
1,214,648
Messages
6,120,725
Members
448,987
Latest member
marion_davis

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top