Search code examples
vb6

How to get previous month and year


How to get previous month and year

Code

Dim dtr As String
text1.Text = "01/2011" 'User Input.... (mm/yyyy)
dtr = text1.Text

If user selected 01/2011 then date should display previous month and year...

Expected Output

  • If user entered text1.text = "02/2011" then it should display "01/2011"
  • If user entered text1.text = "01/2011" then it should display "12/2010"

Can anyone help me to do this?


Solution

  • Building on the answer I provided on your last question...

    Dim dt As Date
    Dim DaysInLastMonth As Integer
    Dim LastMonth As String
    
    dt = CDate(txtPeriod.Text)
    dt = DateAdd("m", -1, dt)
    LastMonth = Format$(dt, "mm/yyyy")
    DaysInLastMonth = DateDiff("d", dt, DateAdd("m", 1, dt))
    
    MsgBox LastMonth & vbCrLf & DaysInLastMonth