Excel VBA: Date Comparison - vba

So I'm currently trying to make a code to compare the current date to two other dates in order to determine the validity of information. For example, if the date is between the first quarter of the year and the second quarter, the information on the document is as of the first quarter date (March 31). Below is what I currently have and for some reason even though the current date is in July, the code keeps saying the information is valid as of March 31. Anyone have any suggestions?
crntDate = Date
q1End = CDate("Mar 31" & " " & Year(Date))
q2End = CDate("Jun 30" & " " & Year(Date))
q3End = CDate("Sep 30" & " " & Year(Date))
q4End = CDate("Dec 31" & " " & Year(Date))
If q1End <= crntDate <= q2End Then
quart = "Q1" & " " & Year(Date)
ElseIf q2End <= crntDate <= q3End Then
quart = "Q2" & " " & Year(Date)
ElseIf q3End <= crntDate <= q4End Then
quart = "Q3" & " " & Year(Date)
Else
quart = "Q4" & " " & Year(Date)
End If
shName = "Quarterly Reporting for" & " " & firstName & " " & lastName & " " & "(" & quart & ")"
With wdApp.ActiveDocument
.SaveAs2 "https://path/" & shName & ".docx"
.Close
End With

If you're trying to format dates as quarters, you don't need all of the end dates and comparisons, you can just use integer division \ in VBA.
Sub test()
Dim quart As String
quart = GetDateAsQuarterYear(VBA.Date)
shName = "Quarterly Reporting for" & " " & firstName & " " & lastName & " " & "(" & quart & ")"
With wdApp.ActiveDocument
.SaveAs2 "https://path/" & shName & ".docx"
.Close
End With
End Sub
Function GetDateAsQuarterYear(crntDate As Date) As String
Dim quarterEnd As Date
quarterEnd = DateSerial(Year(crntDate), 1 + 3 * (1 + (Month(crntDate) - 1) \ 3), 0)
GetDateAsQuarterYear = "Q" & 1 + (Month(crntDate) - 1) \ 3 & " (" & Format$(quarterEnd, "mmmm d, yyyy") & ")"
End Function

q1End <= crntDate <= q2End does not work in Excel it needs to be:
q1End <= crntDate and crntDate <= q2End
So
crntDate = Date
q1End = CDate("Mar 31" & " " & Year(Date))
q2End = CDate("Jun 30" & " " & Year(Date))
q3End = CDate("Sep 30" & " " & Year(Date))
q4End = CDate("Dec 31" & " " & Year(Date))
If q1End <= crntDate and crntDate <= q2End Then
quart = "Q2" & " " & Year(Date)
ElseIf q2End <= crntDate and crntDate <= q3End Then
quart = "Q3" & " " & Year(Date)
ElseIf q3End <= crntDate and crntDate <= q4End Then
quart = "Q4" & " " & Year(Date)
Else
quart = "Q1" & " " & Year(Date)
End If
shName = "Quarterly Reporting for" & " " & firstName & " " & lastName & " " & "(" & quart & ")"
With wdApp.ActiveDocument
.SaveAs2 "https://path/" & shName & ".docx"
.Close
End With

Related

Cannot interpret a BASIC file querying SQL

So, I am trying to figure out where the TOTAL_CHG is coming from. Below is a snippet of where it is first used (not defined at all before).
...
sStrBalance = " (TOTAL_CHG - (ISNULL((SELECT SUM(isnull(t.amount, 0)) FROM transactions t " & _
" WHERE cp.contpolid = t.contpolid AND t.tran_date <= '" & GRepdate & "'), 0) + " & _
" ISNULL((SELECT SUM(isnull(dirpayamt, 0)) FROM bkrtrans bkr " & _
" WHERE cp.contpolid = bkr.contpolid), 0))) "
...
And then the next block of code that references it again is as follows:
...
strSQL = strSQL & vbCrLf & " SELECT cp.Contpolid, cp.CTYPE_ID, cp.C#, cp.REV, " & _
vbCrLf & "CASE WHEN cp.Div_Code = 'GM' THEN 'SLP' ELSE 'SCA' END, " & _
vbCrLf & "cp.Effective_ as EFFDATE, ADJUSTMENT, cp.terminatio, cp.TOTAL_CHG, " & _
vbCrLf & " ISNULL((SELECT SUM(isnull(t.amount, 0)) FROM transactions t " & _
vbCrLf & " WHERE cp.contpolid = t.contpolid AND t.tran_date <= '" & GRepdate & "'), 0) AS Payments, " & _
vbCrLf & " ISNULL((SELECT SUM(isnull(dirpayamt, 0)) FROM bkrtrans bkr " & _
vbCrLf & " WHERE cp.contpolid = bkr.contpolid), 0) AS BrkPayment, " & _
sStrBalance & " AS Balance, cast(0 as numeric(12,2)) as SixtyDays, cast(0 as numeric(12,2)) as NinetyDays , " & _
vbCrLf & " cast(0 as numeric(12,2)) as OverNinetyDays , CASE WHEN Register_D IS NULL THEN 'N' ELSE CASE WHEN Register_D < '" & GRepdate & "' THEN 'Y' ELSE 'N' END END "
strSQL = strSQL & vbCrLf & " FROM CONTRACTS_POLICIES cp (NOLOCK) /*JOIN Salesmen s (NOLOCK) ON s.salesmenid = cp.sales1*/ " & _
vbCrLf & " Where cp.CTYPE_ID = 1 And cp.Cancel_dat Is Null and CP.Sales1 is Not NULL " & _
vbCrLf & " AND ((CP.Effective_ <= '" & GRepdate & "' AND CP.Rev = 0) OR (CP.Adjustment <= '" & GRepdate & "' AND CP.Rev > 0)) " & _
vbCrLf & " AND NOT((" & sStrBalance & " > 0 AND cp.Effective_ <= '01/01/1996') OR (" & sStrBalance & "< 0 AND cp.Effective_ <= '01/01/1998')) " & _
vbCrLf & " And " & sStrBalance & " <> 0 "
...
What table is it even coming from? It seems like it is defined in the first block of code but isn't really a value yet.

Simple VBA: Calc an Array Formula or 255 Char Limit Workaround?

I need a .FormulaArray inserted into my worksheet, however it is well over the 255 character limit (it's 420). I've tried the .Replace workaround, but it doesn't work. Using .Formula = will get it into the cell, but it doesn't calculate and produces #VALUE!, so I would have to crtl+shift+Enter manually. Is there a way VBA can replicate this?
.Cells(Application.WorksheetFunction.Match("Red Car", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value & " " & Year(Date), .Range("A6:BZ6"), 0)).FormulaArray = "=INDEX('" & Root & sourceSheet & ws.Name & " " & "SUM" & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$D:$D,MATCH(""Dealer1"",'" & Root & sourceSheet & ws.Name & " " & "SUM" & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$A&'" & Root & sourceSheet & ws.Name & " " & "SUM" & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$B:$B,0))"
The .Replace setup I'm using is:
Dim theFormulaPart1 As String
Dim theFormulaPart2 As String
theFormulaPart1 = "=INDEX('" & Root & sourceSheet & ws.Name & " " & "SUM" & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$D:$D,MATCH(""Dealer1"",'" & Root & sourceSheet & ws.Name & " " & "X_X_X())"
theFormulaPart2 = "&" & "SUM" & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$A&'" & Root & sourceSheet & ws.Name & " " & "SUM" & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$B:$B,0))"
.Cells(Application.WorksheetFunction.Match("Red Car", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value & " " & Year(Date), .Range("A6:BZ6"), 0)).FormulaArray = theFormulaPart1
.Cells(Application.WorksheetFunction.Match("Red Car", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value & " " & Year(Date), .Range("A6:BZ6"), 0)).Reaplce "X_X_X())", theFormulaPart2

VBA - Get all value in Array as subsequent strings

I have connected VBA & SQL Database in order to pull information.
I have written a script that returns exactly what I want but I would like to make it dynamical (Change years used etc.) and I am here running into problems.
I need to have a special line in my SQL Query which only has 1 thing that changes between the lines (Number of lines need to change and the Case when y.Date_Year = )
I get an Error message in the below code saying that there is a Type mismatch at the " & " sign right above my "period ()" array.
Sub test()
Dim SQLDB As ADODB.Connection
Dim sQuery As String
Dim info()
Dim Start_D As String
Dim End_D As String
Dim Numerator_Used As String
Dim Denominator_Used As String
Dim Number_Years As Integer
Dim period()
Numerator_Used = Range("Numerator")
Denominator_Used = Range("Denominator")
Start_D = Range("Start_Date")
End_D = Range("End_Date")
Range("A11:J100000").Cells.ClearContents
Number_Years = End_D - Start_D
ReDim period(Number_Years + 1)
For i = 0 To Number_Years
period(i + 1) = ",sum(case when y.date_year = " & Start_D + i & " then n." & Numerator_Used & " end) / sum(case when y.date_year = " & Start_D + i & " then s." & Denominator_Used & " end) as '" & Numerator_Used & "/" & Denominator_Used & " " & Start_D + i & "' & _ "
Next i
' Get Margin Expectation Changes
sQuery ="select m.date_month" & _
" m.date_month " & _
period() & _
" from " & Numerator_Used & " as n" & _
" inner join " & Denominator_Used & " as s on s.company_id = n.company_id" & _
" and s.date_month_id = n.date_month_id" & _
" and s.date_year_id = n.date_year_id" & _
" inner join date_year as y on y.date_year_id = n.date_year_id" & _
" inner join date_month as m on m.date_month_id = n.date_month_id" & _
" where y.date_year between " & Start_D & " and " & End_D & " " & _
" and n." & Numerator_Used & " <> 0" & _
" and s." & Denominator_Used & " <> 0" & _
" group by m.date_month;"
Set rs = Common.SQL_Read(SQLDB, sQuery)
ThisWorkbook.Worksheets("Sheet1").Range("A11").CopyFromRecordset rs
Set SQLDB = Common.SQL_Close(SQLDB)
End Sub
As i mentioned in the ocmment to the question, you can not explicity convert period() data into string as it is an array of variant data type (each undefined variable is treated as variant data type). You have to loop through the array data, i.e.:
For i = LBound(period()) To UBound(period())
sQuery = sQuery & period(i) & "...."
Next
'finally:
sQuery = "SELECT ... " & sQuery & " ...."
Change the code as i mentioned above and let me know if it works.

SQL ExecuteQuery 3061 error message

I've got this:
sql = "INSERT INTO instroom ( " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"aantal_instroom, " & _
"ctime, " & _
"cuser, " & _
"mtime, " & _
"muser " & _
") "
sql = sql & "SELECT " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"SUM(aantal_instroom), " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "#, " & _
"" & mod_global.RealUserID & ", " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "#, " & _
"" & mod_global.RealUserID & " " & _
"FROM tmp_import_instroom " & _
"WHERE userid = '" & EscapeString(LCase(mod_global.RealUser)) & "' " & _
"AND team_id <> 0 " & _
"AND proces_id <> 0 "
sql = sql & "GROUP BY team_id, proces_id, datum " & _
"HAVING SUM(aantal_cases) > 0 "
When it goes through:
-- Execute Query
Private Function executeSQL(ByVal sql As String, Optional ByVal autoCommit As Boolean = False) As Boolean
On Error GoTo executeSQLError
executeSQL = False
If mod_global.DevStart Then QueryNum = QueryNum + 1
If mod_global.DevStart Then Call saveQueryToFile(sql)
' Check if database is open
If Not testConn Then
Call openDB
End If
If startTrans Then
db.Execute sql
executeSQL = True
If autoCommit Then
executeSQL = commitDB
End If
End If
DoEvents
Exit Function
executeSQLError:
Debug.Print ("executeSQL - " & Err.Number & " : " & Err.Description)
Call writeToLog("executeSQL - " & Err.Number & " : " & Err.Description)
End Function
I get the error message
"Runtime Error 3061: Too few parameters. Expected 1.".
What am I missing? I did debug.print and still can't find something wrong.
Here are my column names from tmp_import_instroom:
results of debug.print
insert into instroom (
team_id
, proces_id
, datum
, aantal_instroom
, ctime
, cuser
, mtime
, muser
)
select
team_id
, proces_id
, datum
, SUM(aantal_instroom)
, #2017-02-23 20:22:33#
, 310
, #2017-02-23 20:22:33#
, 310
from tmp_import_instroom
where userid = 'xg30222'
and team_id <> 0
and proces_id <> 0
group by team_id
, proces_id
, datum
having SUM(aantal_cases) > 0
Unless it's not showing, there's no ctime, cuser, mtime or muser in your table. Therefore, you need to alias your calculated fields.
sql = sql & "SELECT " & _
"team_id, " & _
"proces_id, " & _
"datum, " & _
"SUM(aantal_instroom) as aantal_instroom, " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "# as ctime, " & _
"" & mod_global.RealUserID & " as cuser, " & _
"#" & Format(MTime, "yyyy-mm-dd hh:mm:ss") & "# as mtime, " & _
"" & mod_global.RealUserID & " as muser " & _
"FROM tmp_import_instroom " & _
"WHERE userid = '" & EscapeString(LCase(mod_global.RealUser)) & "' " & _
"AND team_id <> 0 " & _
"AND proces_id <> 0 "

Copying data without opening workbook using Excel VBA

I'm intending to copy data from one workbook to another through a macro. However, I'm using an Add-In my company has created, which prohibits more than one workbook to be open at once.
Application.ScreenUpdating = False
CurrentYear = Year(Date)
CurrentMonth = Month(Date)
StartDate = DateAdd("m", MonthOffset, Date)
MonthNo = Month(StartDate)
YearNo = Year(StartDate)
path2 = IIf(MonthNo >= 10, Dir("C:\path\filename " & YearNo & "-" & MonthNo & ".xlsx"), Dir("C:\path\filename " & YearNo & "-0" & MonthNo & ".xlsx"))
p2file = "C:\path"
Varrr = IIf(MonthNo >= 10, p2file & path2 & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!", p2file & path2 & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!")
i = 0
Do While Len(path2) > 0
Varrrcell = Cells(3,4+i).Address(RowAbsolute:=False, ColumnAbsolute:=False)
Varrr = Varrr & Varrrcell
currentWb.Sheets("Blad1").Cells(27, 2 + i + 12 * (YearNo Mod 2015)).Formula= "=Varrr"
i = IIf(i > 12, 1, i + 1)
YearNo = IIf(i > 12, YearNo + 1, YearNo)
path2 = IIf(i >= 10, Dir("C:\path\filename " & YearNo & "-" & i & ".xlsx"), Dir("C:\path\filename" & YearNo & "-0" & i & ".xlsx"))
Varrr = IIf(i >= 10, p2file & path2 & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!", p2file & path2 & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!")
Loop
Application.ScreenUpdating = True
EDIT: I've recoded my work to reference to the workbook directly using formula. This solution actually returns the correct path, file and cell I want to copy so that works as intended. However, it returns "Varrr" in each cell. How can I make it return the value instead of the variable name?
EDIT2: I've also contatenated "='" before path2 & p2file & ".." when creating and updating Varrr, and simply saying that
currentWb.Sheets("Blad1").Cells(27, 2 + i + 12 * (YearNo Mod 2015)).Formula= Varrr
but this causes error 1004
EDIT3: I've also added a "closing" ' before the name of the sheet. It did not help.
EDIT4: I've also tried to omit the equal signs, and contenated Varrr = Varrr & Varrcell
and subsequentially put:
currentWb.Sheets("Blad1").Cells(27, 2 + i + 12 * (YearNo Mod 2015)).Formula = "=" & varrr
but it gives code 1004 in the same code snippet. "Application-defined or Object-defined error"
EDIT 5:
Trying to incorporate ExecuteExcel4Macro I've tried the following solution, where Dim ReturnedValue as String:
Varrr = "'" & p2file & "[filename.xlsx " & YearNo & "-" & MonthNo & ".xlsx]Sheetname!'"
ReturnedValue = Varrr & Range("D3").Adress(True,True,-4150)
MsgBox ExecuteExcel4Macro(ReturnedValue)
where the MsgBox gives function error 1004. Here I have trimmed it down a bit to omit the "IIf" statement and the Do loop as I Believe these are redundant in the context.