简体   繁体   中英

Multiple variables from a single user input

I'm writing some VBA code that should go through all Excel files in a specific folder (folder names always formatted with Month Year, eg May 2020). In my code I also need to use the individual "Month" and "Year" strings eg "May" and "2020", and the date format mm/??/yy eg 5/??/20 (the day doesn't matter, so I just put? as a placeholder) which are stored as variables.
So far, I am using Application.FileDialog(msoFileDialogFolderPicker) to let the user choose the folder, and I'm using InputBox("") three times to get the strings and date.
Is there a way to condense this so that the user only has to do one to two things, instead of four?
According to this answer combo box in a date format it seems like a combo box could work (maybe getting the month and year inputs as strings and getting the folder and date based on that?), but is there a better a way?
Any help would be appreciated!

This is the way it might work.

  1. Ask the user for a date
  2. From the date the macro creates the folder name
  3. The path of the folder is stored in the macro

The code below implements and supports that work flow.

Sub GetFolderName()

    Dim Inp             As String
    Dim FolderName      As String
    Dim FilePath        As String
    
    
    ' make sure you ask for a date format that your computer can recognise
    ' it depends upon your Regional Settings (in Windows Control Panel)
    Do
        Inp = InputBox("Enter a date", "Date format dd/mm/yy", _
                       Format(Date, "dd/mm/yy"))
        If Inp = "" Then Exit Sub           ' blank or Cancel
        
        If Not IsDate(Inp) Then
            MsgBox "Sorry, I can't recognise your entry" & vbCr & _
                   "as a date. Please observe the date" & vbCr & _
                   "format requirement and try again."
        End If
    Loop While Not IsDate(Inp)
    
    FilePath = Environ("userprofile") & "\Desktop\"
    FolderName = Format(CDate(Inp), "mmmm yyyy")
    
    MsgBox "Folder name is """ & FolderName & """" & vbCr & _
           "File path = " & FilePath
    
    ' complete path is
    Debug.Print FilePath & FolderName
End Sub

Note that the following options were not utilized but are still available.

Day(Cdate(Inp))    ' returns the day of the entered date
Month(Cdate(Inp))  ' returns the number of the month of the entered date
Year(Cdate(Inp))   ' returns the year of the entered date (45-digit)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM