Предполагая, что вы хотите указать день недели и дату (в формате YYYY/MM/DD
) для каждой даты, которая включает:
- Дата начала
- Следующие 14 дней
Итак, на сегодня (2019-03-26) вы хотели бы получить следующие результаты:
+-----------+------------+
| Weekday | Date |
+-----------+------------+
| Tuesday | 2019/03/26 |
| Wednesday | 2019/03/27 |
| Thursday | 2019/03/28 |
| Friday | 2019/03/29 |
| Saturday | 2019/03/30 |
| Sunday | 2019/03/31 |
| Monday | 2019/04/01 |
| Tuesday | 2019/04/02 |
| Wednesday | 2019/04/03 |
| Thursday | 2019/04/04 |
| Friday | 2019/04/05 |
| Saturday | 2019/04/06 |
| Sunday | 2019/04/07 |
| Monday | 2019/04/08 |
| Tuesday | 2019/04/09 |
+-----------+------------+
Я думаю, что вам лучше всего создать массив, который будет содержать оба отформатированныхдата и день недели, а затем поместите этот массив в нужный диапазон, все сразу, в конце:
Option Explicit
' declare a constant for the number of dates, to avoid hard-coding it later on.
Private Const NUMBER_OF_DATES As Integer = 15
Public Sub InputDate()
' this is your array that will hold the values you need.
' note that we'll initialize is later with the ReDim command.
Dim datesWithWeekdays() As Variant
' this will hold the user i
Dim startDate As Date
' this is your initial user input (a String value).
' you may want to change the variable name to something
' that more closely matches your StartDate (e.g. startDateAsString)
Dim mbox As String
' This is just your counter variable; same as you had before.
Dim i As Integer
' this is a placeholder, to store the date each iteration.
Dim dt As Date
' this is used at the end to put the contents of your array into Excel.
Dim dest As Excel.Range
' here we actually initialize the array.
' the number of rows = the number of dates,
' and the number of columns is 2.
ReDim datesWithWeekdays(1 To NUMBER_OF_DATES, 1 To 2)
mbox = InputBox("Enter Start Date")
If IsDate(mbox) Then
startDate = CDate(mbox)
' note that we don't do any processing outside the loop.
' for the total # of dates (15), calculate the date,
' and then assign the appropriate values to the array.
' note that I'm using the DateAdd function, which is clearer
' than just adding a number to a date.
' Also, I'm adding a "'" character in front of the YYYY/MM/DD,
' so Excel doesn't try to parse it as a date.
' If you want to keep it as a date, and have the format match,
' you can instead change the column formatting in Excel.
For i = 1 To NUMBER_OF_DATES
dt = DateAdd("d", i - 1, startDate)
datesWithWeekdays(i, 1) = Format(dt, "dddd")
datesWithWeekdays(i, 2) = "'" & Format(dt, "YYYY/MM/DD")
Next i
' here, we set up the destination range, and set its value
' to the array.
Set dest = Excel.Range("$D$2")
Set dest = dest.Resize(rowsize:=NUMBER_OF_DATES, columnsize:=2)
dest.Value = datesWithWeekdays
Else
MsgBox "Invalid date"
End If
End Sub