Excel dates table intersection with VBA - vba

I have one excel page and I store date type datas. This datas extra workdays and plus holidays in every year. Other table in this page has start and end date. I would like to show some interval the employees work days. I would like to use the VBA. How to solved this problem?

Use NETWORKDAYS.INTL()
=NETWORKDAYS.INTL(E2,F2,1,A2:A3)

This pictures the Excel table and my code:
Dim startDate As Date
Dim endDate As Date
Dim retValue As Integer
Dim days As Variant
Dim dates As Variant
days = Worksheets("Tényleges munkanapok").ListObjects("TáblázatKorrekciósNapok").DataBodyRange.Value
dates = Worksheets("Tényleges munkanapok").ListObjects("TáblázatSzámoló").DataBodyRange.Value
Dim i As Integer
Dim actualDate As Date
startDate = days(1, 1)
actualDate = dates(1, 1)
Dim CountVariant As Integer
CountVariant = UBound(days)
i = 0
Do While i <= CountVariant
If startDate < actualDate Then
i = i + 1
End If
Loop

Related

Getting all the dates between two selected dates

Good afternoon, I'm new to programming and I'm working with VB.NET.
I need to get the difference between two dates and then list all the intermediate dates in listbox1. I tried the following code but it doesn't work.
Private Sub breaks()
Dim date1 As Date = DateTimePicker1.Value.ToString("dd/MM/yyyy")
Dim date2 As Date = DateTimePicker2.Value.ToString("dd/MM/yyyy")
While date1 <= date2
Dim result = date1
ListBox1.Items.Add(result)
Dim term = 1
date1 = DateTimePicker1.Value.AddDays(term)
End While
End Sub
The function is called within a button. When executed it only shows the sidebars but is blank.
The image shows start date 03/10/2020 and end date 03/16/2020, however the result (listbox) does not return anything.
I expected my result to come:
03/10/2020
03/11/2020
03/12/2020
03/14/2020
03/15/2020
03/16/2020
the interval between them.
Can anyone tell me what's wrong?
You can use some linq for a simple solution
ListBox1.DataSource =
Enumerable.Range(0, 2 + DateTimePicker2.Value.Subtract(DateTimePicker1.Value).Days).
Select(Function(offset) DateTimePicker1.Value.AddDays(offset)).
ToList()
It generates a list of numbers to act as the offset from the initial date, then adds them the specified number of times (different between the dates in days) to create all the dates. No loop required.
Credit to this answer
Edit:
This can also be similarly applied to a DataGridView, but in order to make a single column, we would need to select an anonymous type.
DataGridView1.DataSource =
Enumerable.Range(0, 2 + DateTimePicker2.Value.Subtract(DateTimePicker1.Value).Days).
Select(Function(offset) New With {.Date = DateTimePicker1.Value.AddDays(offset)}).
ToList()
You should avoid using strings for datetimes until they need to be text.
The variable date1 can be used for all the dates, like this:
Dim date1 As Date = DateTimePicker1.Value
Dim date2 As Date = DateTimePicker2.Value
While date1 <= date2
ListBox1.Items.Add(date1.ToString("MM/dd/yyyy"))
Dim term = 1
date1 = date1.AddDays(term)
End While
Also, you should make sure to set Option Strict On as the default for new projects, and set it for the current project.

VBA - Date Format "mm/dd/yyyy"

My excel file format for date is Mar 30 2016 10:12:27:396AM i want to change the format to mm/dd/yyyy. but i'm having an error on my code..
Run-time error '13': Type mismatch
this is the line i got the error SecondDate = Trim(Sheet2.Range("B" & RowNo).Value)
Note: The data from Column A and B are dates
My Code:
Dim Result, RowNo As Long
Dim FirstDate As Variant
Dim SecondDate As Variant
RowNo = 2
FirstDate = Trim(Sheet2.Range("A" & RowNo).Value)
SecondDate = Trim(Sheet2.Range("B" & RowNo).Value)
FirstDate = Format(FirstDate, "mm/dd/yyyy")
SecondDate = Format(SecondDate, "mm/dd/yyyy")
Do Until Sheet2.Cells(RowNo, 1) = ""
FirstDate = Sheet2.Cells(RowNo, 1)
SecondDate = Sheet2.Cells(RowNo, 2)
If DateDiff("d", FirstDate, SecondDate) >= 15 Then
Sheet2.Cells(RowNo, 3) = "1"
Sheet2.Cells(RowNo, 4) = "2"
End If
RowNo = RowNo + 1
Loop
i do feel like im in the right path..am i missing something?
Update: My script will get the data from Column A and Column B and using the DateDiff function i will subtract both columns if the difference is <15 tag it from Column C and D as 1, 2
note:
i only subtract the days from both columns.. but is it possible to subtract both days and years?
it's working if i use the format mm/dd/yyyy in the excel but if i use other format i got the error mismatch
Updated 2:
Column A | Column B | Column C
Mar 1 2016 10:12:27:396AM | Mar 30 2016 10:12:27:396AM |
Mar 1 2016 10:12:27:396AM | Mar 30 2016 10:12:27:396AM |
in my file this is the date format, if you try this as sample data it won't work maybe because VBA doesnt recognize this as dateformat?
Perhaps this will address what you are trying to do.
Test Input:
Test Output:
Code:
Sub DateStuff()
Dim FirstDate As Range, SecondDate As Range
Dim RowNo As Long
Set FirstDate = Sheet4.Range("A1")
Set SecondDate = Sheet4.Range("A2")
FirstDate.NumberFormat = "mm/dd/yyyy"
SecondDate.NumberFormat = "mm/dd/yyyy"
RowNo = 2
Do Until Sheet4.Cells(RowNo, 1) = ""
Set FirstDate = Sheet4.Cells(RowNo, 1)
Set SecondDate = Sheet4.Cells(RowNo, 2)
If IsDate(FirstDate.Value) And IsDate(SecondDate.Value) Then
If DateDiff("d", FirstDate, SecondDate) >= 15 Then
Sheet4.Cells(RowNo, 3) = 1
Sheet4.Cells(RowNo, 4) = 2
End If
End If
RowNo = RowNo + 1
Loop
End Sub
Please spend a few minutes to understand this code:
FirstDate and SecondDate are Range data types, not Date or Variant. The data in the cells they point to are Date or something else.
When setting the format, it sets how it is displayed on the worksheet. It is not formatting a character string in VBA.
Before making the DateDiff call, ensure both FirstDate and SecondDate really contain Date datatypes in the cells, this will prevent many errors.
Operations on Date datatypes using Date functions are NOT dependent on formatting. They use the internal Date type. Formatting ONLY affects how a date is converted to a string and/or displayed on the worksheets.
You asked about checking year instead of day. There are built in VBA functions (e.g. Year, Month, etc.) that will help with this.
As to your update to your question:
I am not sure where you are getting your time codes from, but Excel does not recognize :000 for milliseconds. It uses .000. See below ...

Find Quarter of DateTimePicker Selected Date

I have a DateTimePicker named dtpDateSelection. When I select a date I need to break the date down into two variables. I need Quarter to equal the quarter that the date is in. And I need Year to equal the year that the date is in. I thought I knew how to do this but I'm having trouble. Here is the code I've tried:
Dim Year As String = DatePart("yyyy", dtpDateSelection)
Dim Quarter As String = DatePart("q", dtpDateSelection)
And this is the error I get:
Additional information: Argument 'DateValue' cannot be converted to type 'Date'.
A simple solution:
Dim year As Integer = DateTimePicker.Value.Year
Dim quarter As Integer = ((DateTimePicker.Value.Month - 1) \ 3) + 1
So you have the DateTime value from the DateTimePicker.Value property.
Using that you can retrieve the year of the date, like this:
Dim year As Integer = DateTimePicker.Value.Year
For determining the quarter the date is within, try this:
Public Shared Function DetermineQuarter(dateTime As DateTime) As Integer
If dateTime.Month <= 3 Then
Return 1
End If
If dateTime.Month <= 6 Then
Return 2
End If
If dateTime.Month <= 9 Then
Return 3
End If
Return 4
End Function
Now you can get the quarter value, like this:
Dim quarter As Integer = DetermineQuarter(DateTimePicker.Value)
As others pointed out, a DateTime value has a .Month member. For the quarter, I have always used a simple Choose function
Dim quarter As Integer = Choose(DateTimePicker1.Value.Month, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4)
Beyond that, your two lines of code work, but you need to add the .Value to the end of dtpDateSelection. The DatePart function 2nd parameter has an Object type, so it will allow you to pass in a control (which is what you are doing), but the end result will be an error. The .Value changes it to the date selected in the picker.
Dim Year As String = DatePart("yyyy", dtpDateSelection.Value)
Dim Quarter As String = DatePart("q", dtpDateSelection.Value)

Concatenating variables

I'm trying to create an expiration date using values selected from drop down lists on my web form, however I am unable to concatenate the Month variable value and Year variable value. I get the error: Error Operator '&' is not defined for types 'String' and System.Web.UI.WebControls.ListItem'. I have tried to use the "+" also but get the same error.
Here is the code I have:
Dim Month = monthDropDownList.SelectedValue
Dim Year = yearDropDownList.SelectedItem
Dim MonthYear = Month & Year
Dim ExpirationDate As Date = MonthYear
Any help would be greatly appreciated.
You don't want SelectedItem. You want SelectedValue. You should also explicitly declare your variables. You also can't create a Date in this manner. You need to use integers.
Dim Month As Integer= Convert.ToInt32(monthDropDownList.SelectedValue)
Dim Year as Integer = Convert.ToInt32(yearDropDownList.SelectedValue)
Dim ExpirationDate As Date = New Date(Year, Month, 1)
As a slight "cleaner" way to do this I would use:
Dim Month as Integer
Dim Year As Integer
Dim ExpirationDate As Date
Integer.TryParse(monthDropDownList.SelectedValue, Month)
Integer.TryParse(yearDropDownList.SelectedValue, Year)
If (Month > 0 AndAlso Year > 0) Then
ExpirationDate = New Date(Year, Month, 1)
End If

Datediff() function not getting the expected result in VB.NET

I am using the following code in my project. I want to find the number of days by given the last date and now.
Dim BorrowDate As Date
Dim i As Integer
BorrowDate = Date.Parse(txtBorrowDate.Text)
i = DateDiff(DateInterval.Day, BorrowDate, DateTime.Now)
for example, when BorrowDate is "01/Jul/2011" then the result is 7 days which it should be 10 to now. Please help
Since you are using .Net you might try this
Dim BorrowDate As Date = Date.Parse(txtBorrowDate.Text)
Debug.WriteLine(BorrowDate.ToString)
Debug.WriteLine(DateTime.Now.ToString)
Dim ts As TimeSpan = DateTime.Now - BorrowDate
Dim numdays As Integer = CInt(ts.TotalDays)
Debug.WriteLine(numdays.ToString("n0"))
edit: Init the variables and show the dates.