вставить день недели в формате ГГГГ / ММ / ДД - PullRequest
0 голосов
/ 26 марта 2019

Я пытаюсь получить день недели, который будет представлен на основе существующей даты в столбце.Например, 2019/03/26 будет отображаться в одном столбце, а в соседнем столбце будет присутствовать / инстанцироваться слово / дата вторника

Sub InputDate()

Dim StartDate As Date
Dim DayOfWeek As Date
Dim i As Integer

mbox = InputBox("Enter Start Date", "Enter Start Date")

If IsDate(mbox) Then
StartDate = CDate(mbox)
Range("d2") = StartDate

    For i = 1 To 14
        Cells(i + 1, 4).Value = StartDate + i
    Next i

Range("d2").CurrentRegion.Offset(, -1).Value = "Eg Tuesday"

Else
MsgBox "Please Enter a Date"
End If

End Sub

Таким образом, конечный результат будет выглядеть как

Вторник 2019/03/26

Среда 2019/03/27

Я думаю, что я могу столкнуться с двумя проблемами.

Первое, что я не могуизвлекать день недели из даты, представленной в стиле style 26.03.2009

Во-вторых, я не уверен, соответствует ли мой метод столбцу C (где я хочудень недели) в столбец D, где указан стиль даты 26.03.2009, является правильным.

Ответы [ 3 ]

1 голос
/ 26 марта 2019

Предполагая, что вы хотите указать день недели и дату (в формате 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
0 голосов
/ 26 марта 2019

если вы хотите потратить дополнительное время без причины, мне нравится делать это таким образом.

if range("h6").value = monday then
   range("i6").value = 15
   range("j6").value = 03
   range("k6").value = 2019
else
  if range("h7").value = tuesday then
     range("i7").value = range("i6").value + 1
  else
   (so on through the rest of the days)
end if
0 голосов
/ 26 марта 2019

Если вы используете VBA, вам нужна функция Format:

Dim StartDate As Date
Dim DayOfWeek As Date
Dim i As Integer

mbox = InputBox("Enter Start Date", "Enter Start Date")

If IsDate(mbox) Then
    StartDate = CDate(mbox)
    For i = 0 To 13
        Cells(i + 2, 3) = Format(StartDate + i, "dddd")
        Cells(i + 2, 4).Value = StartDate + i
    Next i
Else
    MsgBox "Please Enter a Date"
End If

Если вы хотите, чтобы подпрограмма отображала 14 дней , включая введенный день, используйте этот цикл вместо:

For i = 0 To 13
    Cells(i + 2, 3) = Format(StartDate + i, "dddd")
    Cells(i + 2, 4).Value = StartDate + i
Next i
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...