I'm trying to automate the process of compiling quarterly data from different files into a single Excel workbook (this needs to be done each quarter). Now I have come to a point where I wondered if I should keep all code in the main sub or if I should use a function. I really would like to hear from people who have worked with VBA for more than a few months and learn about writing efficient and readable code.
The first thing my code needs to do is getting me three date/date related variables:
- The current year or, in case of Q4 data, the year before that
- Depending on the quarter, a variable that looks like this: 12.31.2018 for Q4 2018; for Q1 2019 it would be 03.31.2019. It's the subfolder name where the relevant files are saved.
- The quarter, so Q1, Q2, Q3 or Q4.
See below for my code and please improve it if something catches your eye. Specifically, I wonder how to name my variables (if you have a variable storing the year, what would you call it?). Also, the Case Else
isn't necessary, right? I mean month(Date)
can only be one of 12 months.
Sub DetermineDate()
Dim qVar As String
Dim yVar As Integer
Dim fullDate As String
yVar = Year(Date) 'set value here or each time in case statement?
Select Case month(Date)
Case 1, 2, 3
qVar = "Q4"
yVar = Year(Date) - 1
fullDate = "12.31." & yVar
Case 4, 5, 6
qVar = "Q1"
fullDate = "03.31." & yVar
Case 7, 8, 9
qVar = "Q2"
fullDate = "06.30." & yVar
Case 10, 11, 12
qVar = "Q3"
fullDate = "09.30." & yVar
Case Else
MsgBox "Error"
Exit Sub
End Select
End Sub
However, my question is: is there any reason not to put this in the main sub? I had this notion that it would be good to focus on the meat of the code (copy-pasting all the data) in the main sub. So I felt it would make sense put the code to determine the date in a separate function. However, I found out returning multiple values is not straightforward and not the intention of a function. Also, I would only call this function a single time, so after some thinking I came to the conclusion it probably doesn't make sense to put this somewhere else. Basically I'm asking what is good practice when using functions and multiple subs.