How to Write this Crystal Report formula in SSRS Expression? - reporting-services

I am Having Problem to Convert this Crystal Report formula in SSRS Expression Can Anyone Help me?
Formula 1:
Dim fromExDay as String
Dim toExDay as String
Dim sYr as String
Dim sMonth as String
Dim sDay as String
fromExDay = ToText({wk_TORIO0460_a.HktrExchngDayFrom})
fromExDay = Replace (fromExDay, ",", "" )
fromExDay = Replace (fromExDay, ".", "" )
toExDay = ToText({wk_TORIO0460_a.HktrExchngDayTo})
toExDay = Replace (toExDay, ",", "" )
toExDay = Replace (toExDay, ".", "" )
if Len (Trim(fromExDay)) > 0 and Len (Trim(toExDay)) > 0 then
sYr = Right(Left(fromExDay, 4),2)
if sYr <> "99" then
sYr = LEFT(CStr(CDbl(sYr) + 12),2)
end if
sMonth = Mid(fromExDay, 5, 2)
sDay = Left(Right(fromExDay, 4),2)
'fromExDay = sYr + sMonth + sDay
fromExDay = sYr + sMonth + sDay
sYr = Right(Left(toExDay, 4),2)
if sYr <> "99" then
sYr = LEFT(CStr(CDbl(sYr) + 12),2)
end if
sMonth = Mid(toExDay, 5, 2)
sDay = Left(Right(toExDay, 4),2)
toExDay = sYr + sMonth + sDay
'toExDay = Right(fromExDay, 2)
Formula = fromExDay + " ~ " + toExDay
Else
Formula = ""
End If
Value of ExchangeFrom and ExchangeTO is coming from Database .
ExchangeFrom value = 20031031
ExchangeTo value = 200
Is There in Database

Is the return value supposed to be
151010 ~ 1220
There actually weren't many changes needed to convert it to an SSRS VB function. In SSRS, the function doesn't work directly with the field so you need to pass them to the function as parameters. Most of the rest of the VB in your old function should work the same in SSRS - I just removed the ToText functions that aren't in SSRS.
When you call the function from your text box, you pass the fields.
=code.Formula1(Fields!HktrExchngDayFrom.Value, Fields!HktrExchngDayTo.Value)
And here's the function:
Public Function Formula1(ByVal fromExDay as String, ByVal toExDay as String) as String
Dim sYr as String
Dim sMonth as String
Dim sDay as String
fromExDay = Replace (fromExDay, ",", "" )
fromExDay = Replace (fromExDay, ".", "" )
toExDay = Replace (toExDay, ",", "" )
toExDay = Replace (toExDay, ".", "" )
if Len (Trim(fromExDay)) > 0 and Len (Trim(toExDay)) > 0 then
sYr = Right(Left(fromExDay, 4),2)
if sYr <> "99" then
sYr = LEFT(CStr(CDbl(sYr) + 12), 2)
end if
sMonth = Mid(fromExDay, 5, 2)
sDay = Left(Right(fromExDay, 4), 2)
fromExDay = sYr + sMonth + sDay
sYr = Right(Left(toExDay, 4), 2)
if sYr <> "99" then
sYr = LEFT(CStr(CDbl(sYr) + 12), 2)
end if
sMonth = Mid(toExDay, 5, 2)
sDay = Left(Right(toExDay, 4), 2)
toExDay = sYr + sMonth + sDay
Formula1 = fromExDay + " ~ " + toExDay
Else
Formula1 = ""
End If
End Function
I think the sDay calculations are incorrect.
sDay = Left(Right(fromExDay, 4),2)
Seems to be getting the month again. It should probably be
sDay = Right(fromExDay, 2)
or, if it can be a longer string use MID:
sDay = Mid(fromExDay, 7, 2)
Which changes the result to:
151031 ~ 12

For making this Formula I Taken Two Textbox in Active Report page and I divided this formula Into two Parts.
Textbox1:
=iif(Right(Left( Fields!ExchngDayFrom.Value , 4),2) <> 99 ,LEFT(CStr(CDbl((Right(Left( Fields!ExchngDayFrom.Value , 4),2) ) + 12),2) + Mid( Fields!ExchngDayFrom.Value , 5, 2) + Left(Right( Fields!ExchngDayFrom.Value , 2),2 ) ," ")
Assuming Value of ExchangeDayfrom is : 20031031
Output is 151031
TextBox2:
="~ " & iif(Right(Left( Fields!ExchngDayTo.Value , 4),2) <> 99 ,LEFT(CStr(CDbl((Right(Left( Fields!ExchngDayTo.Value , 4),2)) + 12),2) + Mid( Fields!ExchngDayTo.Value , 5, 2) + Left(Right( Fields!ExchngDayTo.Value , 2),2 ) , Right(Left( Fields!ExchngDayTo.Value , 4),2) + Mid( Fields!ExchngDayTo.Value , 5, 2) + Left(Right( Fields!ExchngDayTo.Value , 2),2 )
Assuming Value of ExchangeDayTo is : 99999999
Output is ~ 999999
This is How I Solve my Problem.Big thanks to #Hannover Fist sir thanks Your valuable Solution and Yes Your Solution is Right it's also worked Perfectly

Related

how to display long text ( datatype text up to 20 000 characters) in div

I'm currently enhancing a system using vb.net. My issue is, i need to display a column name 'WONOTE' (datatype TEXT) from SQL Server into div in html front screen. The maximum length of characters for this column is up to 22 000 characters. I retrieved the data from SQL server into div by using sql command in code behind. I manage to display the data but only up to 110 characters by using this statement 1:
REPLACE(REPLACE(cast(WONOTE as varchar(110)), CHAR(13), ''), CHAR(10), '')
and up to 10 characters using this statement 2:
CONVERT(VARCHAR(10), b.WONOTE) as WONOTE
but I need it to display full text. If i change into varchar(max) or anything greater than 110 for statement 1 and 10 for statement 2 it display nothing.
I wish someone can help me with it.
Thank you in advance.
How i retrieved data from SQL server:
Public Sub GETWHATSRUNNING()
Dim paraWC As SqlParameter
Dim SQL As String
Dim myArray, myArray1, myArray2, myArray3,
myArray4, myArray5, myArray6, myArray7,
myArray8, myArray9, myArray10 As String
TempDT.Columns.Add("WO", GetType(String))
TempDT.Columns.Add("WOQTY", GetType(String))
TempDT.Columns.Add("PartNum", GetType(String))
TempDT.Columns.Add("Desc", GetType(String))
TempDT.Columns.Add("WIPQTY", GetType(String))
TempDT.Columns.Add("WIPDAYS", GetType(String))
TempDT.Columns.Add("WOAGING", GetType(String))
TempDT.Columns.Add("AGINGATWC", GetType(Double))
TempDT.Columns.Add("COLOR", GetType(String))
'TempDT.Columns.Add("WO_NOTE", GetType(String))
WCLimit = 5
SQL = "select distinct A.WONO, B.BLDQTY , C.PART_NO , C.DESCRIPT, B.Start_Date, REPLACE(REPLACE(cast(WONOTE as varchar(110)), CHAR(13), ''), CHAR(10), '') " & _
"from Transfer A " & _
"left join WOENTRY B on A.wono = B.wono " & _
"left join INVENTOR C on B.UNIQ_KEY = C.UNIQ_KEY " & _
"where FR_DEPT_ID = #WC and start_date is not null " & _
"and B.BLDQTY <> B.COMPLETE "
GetConnection()
oConnSql = New SqlConnection(connString.ToString)
oCmdSql = New SqlCommand(SQL, oConnSql)
paraWC = New SqlParameter("#WC", SqlDbType.VarChar, 5)
paraWC.Value = lblWC.Text
oCmdSql.Parameters.Add(paraWC)
oCmdSql.CommandTimeout = 7200
Try
If oConnSql.State = ConnectionState.Closed Then
oConnSql.Open()
End If
' Adapter and Dataset
oAdptSql.SelectCommand = oCmdSql
oAdptSql.Fill(oDS, "dtList")
oAdptSql.Fill(dt)
If dt.Rows.Count > 0 Then
Dim ProgessQty, WIPQty, WOQuantity As String
Dim AgingWC, WOAging As Double
'Dim WCAge, WoAge As TimeSpan
Dim LeadTime As Double
Dim Holiday As Integer
Dim counter As Integer = 1
Dim count As Integer = dt.Rows.Count - 1
For i = 0 To count - 1
ProgessQty = GETProgressWOQuantity(Trim(dt.Rows(i)(0).ToString))
WOQuantity = Trim(dt.Rows(i)(1).ToString)
WIPQty = CInt(ProgessQty)
LeadTime = GetLeadTime(Trim(dt.Rows(i)(2).ToString), lblWC.Text)
Holiday = CheckForHolidays(CDate(dt.Rows(i)(4).ToString), Now())
WOAging = Format((DateDiff(DateInterval.Minute, CDate(dt.Rows(i)(4).ToString), Now())) / 60 / 24, "0.0") - Holiday
AgingWC = WOAging - LeadTime
If AgingWC >= 5 And WIPQty > 0 Then
TempDT.Rows.Add(Trim(dt.Rows(i)(0).ToString), WOQuantity, Trim(dt.Rows(i)(2).ToString), Trim(dt.Rows(i)(3).ToString), WIPQty, Trim(dt.Rows(i)(5).ToString), Math.Round(CDbl(WOAging), 2), Math.Round(CDbl(AgingWC), 2), IIf(Math.Round(CDbl(AgingWC), 2) >= WCLimit, "Red", "Black"))
'
counter += 1
Else
End If
Next
Dim dataView As New DataView(TempDT)
dataView.Sort = " AGINGATWC DESC"
SortDT = dataView.ToTable()
For j = 0 To SortDT.Rows.Count - 1
myArray = myArray & "|" & j + 1
myArray1 = myArray1 & "|" & Trim(SortDT.Rows(j)(0).ToString) 'WO
myArray2 = myArray2 & "|" & Trim(SortDT.Rows(j)(1).ToString) 'WO QTY
myArray3 = myArray3 & "|" & Trim(SortDT.Rows(j)(2).ToString) 'Part Number
myArray4 = myArray4 & "|" & Trim(SortDT.Rows(j)(3).ToString) 'Description
myArray5 = myArray5 & "|" & Trim(SortDT.Rows(j)(4).ToString) 'WIP QTY
myArray6 = myArray6 & "|" & Trim(SortDT.Rows(j)(5).ToString) 'WIP DAYS
myArray7 = myArray7 & "|" & Trim(SortDT.Rows(j)(6).ToString) 'WO Aging
myArray8 = myArray8 & "|" & Trim(SortDT.Rows(j)(7).ToString) 'Aging at WC
myArray9 = myArray9 & "|" & Trim(SortDT.Rows(j)(8).ToString) 'Color
myArray10 = myArray10 & "|" & Trim(SortDT.Rows(j)(5).ToString) 'WONOTE
Next
dt.Clear()
dt.Dispose()
oCmdSql.Dispose()
oConnSql.Close()
ViewState.Clear()
ViewState("JArray") = myArray
ViewState("JArray1") = myArray1
ViewState("JArray2") = myArray2
ViewState("JArray3") = myArray3
ViewState("JArray4") = myArray4
ViewState("JArray5") = myArray5
'ViewState("JArray6") = myArray6
ViewState("JArray7") = myArray7
ViewState("JArray8") = myArray8
ViewState("JArray9") = myArray9
ViewState("JArray10") = myArray10
End If
Catch ex As Exception
lblResult.Text = "Exception Message: " + ex.Message
Finally
End Try
End Sub
Now I realised if I run in Internet Explorer with varchar(max) it says

Classic ASP inserting variable value into Access DB

I am trying to insert a variable value into my access database, I am able to insert a value that's pre-set like
<td width="125" nowrap="nowrap" ><div align="right">Lead From </div></td>
<td><input name="lead" type="text" id="lead" value="" size="50" /></td>
as you can see we have a id of "lead" and I can insert that into the db fine like this:
MM_fieldsStr = "lead|value";
MM_columnsStr = "Lead|',none,''";
' create the MM_fields and MM_columns arrays
MM_fields = Split(MM_fieldsStr, "|")
MM_columns = Split(MM_columnsStr, "|")
' set the form values
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_fields(MM_i+1) = CStr(Request.Form(MM_fields(MM_i)))
Next
now I want to be able to do something like this:
Session("MM_JobNumber") = job_number
MM_fieldsStr = job_number & "|value"
MM_columnsStr = "Job_Num|',none,''"
when ever i try pass a variable through it returns null, ofc you cant see job number being set in the code i have supplied but it does 100% get set.
COUNTER RECORDER::
Dim countrec
Dim countrec_numRows
Set countrec = Server.CreateObject("ADODB.Recordset")
countrec.ActiveConnection = MM_JobConn_STRING
countrec.Source = "SELECT * FROM CounterTAB WHERE Counter_ID = 1"
countrec.CursorType = 0
countrec.CursorLocation = 2
countrec.LockType = 1
countrec.Open()
countrec_numRows = 0
FULL CODE BELOW::
If (CStr(Request("MM_insert")) = "form2") Then
Dim job_number
IF (Session("MM_JobNumber") <> "") OR (Session("MM_JobNumber") <> NULL)Then
job_number = Session("MM_JobNumber")
Else
Dim new_count_num
new_count_num = countrec.Fields.Item("Counter_NUM").Value+1
job_number = PadDigits(new_count_num, 4) + "-" + mid(DatePart("yyyy",now()),3,2)
Session("MM_JobNumber") = job_number
END IF
'UPDATE COUNTER
set counterupdate = Server.CreateObject("ADODB.Command")
counterupdate.ActiveConnection = MM_JobConn_STRING
counterupdate.CommandText = "UPDATE CounterTAB SET Counter_NUM = Counter_NUM + 1 WHERE Counter_ID = 1"
counterupdate.CommandType = 1
counterupdate.CommandTimeout = 0
counterupdate.Prepared = true
counterupdate.Execute()
MM_editConnection = MM_JobConn_STRING
MM_editTable = "Job_Details"
MM_editRedirectUrl = "view_jobs_new.asp?offset=-1"
MM_fieldsStr = job_number & "|value|hiddenDateRaised|value|hiddenYearRaised|value|hiddenNewRaisedBYID|value|hiddenRaisedBYID|value|hiddenFieldCompanyID|value|hiddenFieldContact1|value|Job_Ref_Name|value|checkbox3_1|value|checkbox3_15|value|checkbox3_4|value|checkbox3_2|value|checkbox3_16|value|checkbox3_5|value|checkbox3_3|value|checkbox3_6|value|checkbox3_7|value|checkbox3_22|value|checkbox3_8|value|checkbox3_9|value|checkbox3_23|value|checkbox3_10|value|checkbox3_20|value|checkbox3_11|value|checkbox3_17|value|checkbox3_12|value|checkbox3_21|value|checkbox3_13|value|checkbox3_18|value|checkbox3_24|value|checkbox3_14|value|checkbox3_19|value|checkbox3_25|value|checkbox3_26|value|DescriptText|value|sitename|value|siteAdd1|value|siteAdd2|value|siteAdd3|value|siteAdd4|value|siteAdd5|value|sitePostCode|value|lead|value"
MM_columnsStr = "Job_Num|',none,''|Job_Date|',none,''|Job_Year|none,none,NULL|New_Raised_By|none,none,NULL|Raised_By|none,none,NULL|Company|none,none,NULL|Contact|none,none,NULL|Job_Ref|',none,''|Scope_3_01_SiteDecom|none,-1,0|Scope_3_15_Spill|none,-1,0|Scope_3_04_TankClean|none,-1,0|Scope_3_02_SiteClosure|none,-1,0|Scope_3_16_EnviroAss|none,-1,0|Scope_3_05_OtherTankClean|none,-1,0|Scope_3_03_GroundRem|none,-1,0|Scope_3_06_TankLining|none,-1,0|Scope_3_07_TankPainting|none,-1,0|Scope_3_22_SaleFuel|none,-1,0|Scope_3_08_ShipTank|none,-1,0|Scope_3_09_VapourRec|none,-1,0|Scope_3_23_SaleRec|none,-1,0|Scope_3_10_Petroscope|none,-1,0|[Scope_3_20_IBC Testing]|none,-1,0|Scope_3_11_Vacutect|none,-1,0|Scope_3_17_FuelSys|none,-1,0|Scope_3_12_TankCalib|none,-1,0|Scope_3_21_FuelSampling|none,1,0|Scope_3_13_5stage|none,-1,0|Scope_3_18_Oftec|none,-1,0|Scope_3_24_SpillKit|none,-1,0|Scope_3_14_Rail|none,-1,0|Scope_3_19_TankerServices|none,-1,0|Scope_3_25_Training|none,-1,0|Scope_3_26_Other|none,-1,0|Job_Description|',none,'' | Site_Name|',none,''|Site_Add1|',none,''|Site_Add2|',none,''|Site_Add3|',none,''|Site_Add4|',none,''|Site_Add5|',none,''|Site_Postcode|',none,''|Lead_From|',none,''"
' create the MM_fields and MM_columns arrays
MM_fields = Split(MM_fieldsStr, "|")
MM_columns = Split(MM_columnsStr, "|")
' set the form values
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_fields(MM_i+1) = CStr(Request.Form(MM_fields(MM_i)))
Next
' append the query string to the redirect URL
If (MM_editRedirectUrl <> "" And Request.QueryString <> "") Then
If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0 And Request.QueryString <> "") Then
MM_editRedirectUrl = MM_editRedirectUrl & "?" & Request.QueryString
Else
MM_editRedirectUrl = MM_editRedirectUrl & "&" & Request.QueryString
End If
End If
End If
INSERT CODE::
' *** Insert Record: construct a sql insert statement and execute it
Dim MM_tableValues
Dim MM_dbValues
If (CStr(Request("MM_insert")) <> "") Then
'here goes counter update
' create the sql insert statement
MM_tableValues = ""
MM_dbValues = ""
For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
MM_formVal = MM_fields(MM_i+1)
MM_typeArray = Split(MM_columns(MM_i+1),",")
MM_delim = MM_typeArray(0)
If (MM_delim = "none") Then MM_delim = ""
MM_altVal = MM_typeArray(1)
If (MM_altVal = "none") Then MM_altVal = ""
MM_emptyVal = MM_typeArray(2)
If (MM_emptyVal = "none") Then MM_emptyVal = ""
If (MM_formVal = "") Then
MM_formVal = MM_emptyVal
Else
If (MM_altVal <> "") Then
MM_formVal = MM_altVal
ElseIf (MM_delim = "'") Then ' escape quotes
MM_formVal = "'" & Replace(MM_formVal,"'","''") & "'"
Else
MM_formVal = MM_delim + MM_formVal + MM_delim
End If
End If
If (MM_i <> LBound(MM_fields)) Then
MM_tableValues = MM_tableValues & ","
MM_dbValues = MM_dbValues & ","
End If
MM_tableValues = MM_tableValues & MM_columns(MM_i)
MM_dbValues = MM_dbValues & MM_formVal
Next
MM_editQuery = "insert into " & MM_editTable & " (" & MM_tableValues & ") values (" & MM_dbValues & ")"
If (Not MM_abortEdit) Then
' execute the insert
Set MM_editCmd = Server.CreateObject("ADODB.Command")
MM_editCmd.ActiveConnection = MM_editConnection
MM_editCmd.CommandText = MM_editQuery
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close
Session("MM_JobNumber") = NULL
If (MM_editRedirectUrl <> "") Then
Response.Redirect(MM_editRedirectUrl)
End If
End If
End If
Split() deals with separators, not delimiters. So the trailing "|" in
MM_columnsStr = "Job_Num|',none,''|"
causes a spurious/empty element in the array. Evidence:
>> s = "Lead|',none,''"
>> a = Split(s, "|")
>> WScript.Echo UBound(a), a(UBound(a))
>>
1 ',none,''
>> s = "Job_Num|',none,''|"
>> a = Split(s, "|")
>> WScript.Echo UBound(a), a(UBound(a))
>>
2
On second thought:
This
>> job_number = "JN"
>> MM_fieldsStr = job_number & "|value"
>> WScript.Echo MM_fieldsStr
>>
JN|value
should prove, that string concatenation works in VBScript. If you get
|value
then job_number is empty before the & line. Perhaps you meant
job_number = Session("MM_JobNumber")
instead of
Session("MM_JobNumber") = job_number
Last thought:
This:
IF (Session("MM_JobNumber") <> "") OR (Session("MM_JobNumber") <> NULL)Then
job_number = Session("MM_JobNumber")
will set job_number only if is not empty or Null.
all that was needed was to pad the job_number string out with ' ' marks at the start and end, hope this helps anyone else trying to do something similar

Convert JSON Date To MM/DD/YYYY Format?

My client receives a spreadsheet with a number of columns, one being a "date". Only the date turns out to be formatted as Date(1292291582263-0700) (a JSON date it seems).
I need to convert and work with this JSON date in MM/DD/YYYY format, elsewhere in this spreadsheet's code (VBA).
Does anyone know how to parse and convert this JSON date format into a MM/DD/YYYY format? I have read lots of solutions on SO that are in Javascript, C#, or ASP.NET, etc but all I have to work with is Excel 2010 and VBA code for this project. Is there way to arrive at a readable format as I need?
Millisecond Epoch time with a +/- offset?
Const test = "1292291582263-0700"
Dim dt As String: dt = Left$(test, 13)
Dim off As String: off = Mid$(test, 14)
Dim d As Date: d = DateAdd("s", CCur(dt) / 1000, "01/01/1970")
Debug.Print d
<<< 14/12/2010 01:53:02
d = DateAdd("h", Left$(off, 3), d)
d = DateAdd("n", Right$(off, 2), d)
Debug.Print d
<<< 13/12/2010 18:53:02
This function take care of date before 1971-01-01 and some problem with overflow.
Public Function Convert_Microsoft_Json_Date_To_Date(strMicrosoftDate As String) As Date
'Convert_Microsoft_Json_Date_To_Date("/Date(-2208970800000-0530)/") => 1900-01-01
'Convert_Microsoft_Json_Date_To_Date("/Date(2208970800000-0530)/") => 2039-12-31 14:00:00
Dim strProcedureName As String: strProcedureName = "Convert_Microsoft_Json_Date_To_Date"
Dim lngDateNumber As Long
Dim strOffsetSign As String
Dim strOffsetHours As String
Dim strOffsetMinutes As String
Dim dteDateNoOffset As Date
Dim dteRealDate As Date
Dim curSecondToAdd As Currency '+ or -
Dim curSecondLeft As Currency
Dim curSecondMax As Currency
Dim IsOffsetExist As Boolean
On Error GoTo err_
strMicrosoftDate = Replace(strMicrosoftDate, "/", "")
strMicrosoftDate = Replace(strMicrosoftDate, "(", "")
strMicrosoftDate = Replace(strMicrosoftDate, ")", "")
strMicrosoftDate = Replace(strMicrosoftDate, "Date", "")
strOffsetSign = Left(Right(strMicrosoftDate, 5), 1)
strOffsetHours = Left(Right(strMicrosoftDate, 4), 2)
strOffsetMinutes = Right(strMicrosoftDate, 2)
IsOffsetExist = strOffsetSign = "+" Or strOffsetSign = "-"
If IsOffsetExist Then
'Remove the offset part if exist
strMicrosoftDate = Left(strMicrosoftDate, Len(strMicrosoftDate) - 5)
End If
curSecondMax = 1000000000# 'if curSecondToAdd is to high we get overflow, and I do it in 2 step below to get my date
curSecondToAdd = CCur(strMicrosoftDate) / 1000 'Convert miliseconds to seconds
If Abs(curSecondToAdd) > curSecondMax Then
If curSecondToAdd >= 0 Then
dteDateNoOffset = DateAdd("s", curSecondToAdd - curSecondMax, DateSerial(1970, 1, 1))
dteDateNoOffset = DateAdd("s", curSecondMax, dteDateNoOffset)
Else
dteDateNoOffset = DateAdd("s", curSecondToAdd + curSecondMax, DateSerial(1970, 1, 1))
dteDateNoOffset = DateAdd("s", -curSecondMax, dteDateNoOffset)
End If
Else
dteDateNoOffset = DateAdd("s", curSecondToAdd, DateSerial(1970, 1, 1))
End If
'Debug.Print "Date no offset: " & dteDateNoOffset
If IsOffsetExist Then
dteRealDate = DateAdd("h", CInt(strOffsetSign & strOffsetHours), dteDateNoOffset)
dteRealDate = DateAdd("n", CInt(strOffsetSign & strOffsetMinutes), dteRealDate)
Else
dteRealDate = dteDateNoOffset
End If
'Debug.Print "Date real: " & dteRealDate
Convert_Microsoft_Json_Date_To_Date = dteRealDate
err_exit:
Exit Function
err_:
Select Case Err.Number
Case Else
MsgBox Err.Description & " | " & Err.Number & vbCrLf & "Procedure: " & strProcedureName & IIf(Erl <> 0, vbCrLf & "Ligne: " & Erl, ""), vbCritical
Resume err_exit
Resume
End Select
End Function

Need to Allow Null or "" values for Dates - Access Query Data type mismatch

Basically I'm trying to use a Module or Public functions to pull a datediff that is only for business days. Everything works as far as the code is concerned but for some reason with a particular date field (one I've added after the database has been in production for some time) the code is not working correctly and I'm getting the "Data Type Mismatch in Expression". I'm 99% sure this is a data problem. If I compare two different dates it runs, I've created a test table with 10 records and it runs.
The field is set to Date/Time. I guess my question is, is there anyway to get rid of the ""'s or make it so the code will accept these blanks as nulls? or convert them?
This is where I call the function in the query:
Exp1: BusinessDays([IntCallDate],[aIntCall1])
And here is the code in the module...
Thanks for any help - MUCH appreciated!!!
Public Function BusinessDays(dteStartDate As Date, dteEndDate As Date) As Long
On Error GoTo err_workingDays
Dim lngYear As Long
Dim lngEYear As Long
Dim dteStart As Date, dteEnd As Date
Dim dteCurr As Date
Dim lngDay As Long
Dim lngDiff As Long
Dim lngACount As Long
Dim dteLoop As Variant
Dim blnHol As Boolean
Dim dteHoliday() As Date
Dim lngCount As Long, lngTotal As Long
Dim lngThanks As Long
If IsDate(dteStartDate) And IsDate(dteEndDate) Then 'added here begin
dteStart = dteStartDate
dteEnd = dteEndDate
lngYear = DatePart("yyyy", dteStart)
lngEYear = DatePart("yyyy", dteEnd)
If lngYear <> lngEYear Then
lngDiff = (((lngEYear - lngYear) + 1) * 7) - 1
ReDim dteHoliday(lngDiff)
Else
ReDim dteHoliday(6)
End If
lngACount = -1
For lngCount = lngYear To lngEYear
lngACount = lngACount + 1
'July Fourth
dteHoliday(lngACount) = DateSerial(lngCount, 7, 4)
lngACount = lngACount + 1
'Christmas
dteHoliday(lngACount) = DateSerial(lngCount, 12, 25)
lngACount = lngACount + 1
'New Years
dteHoliday(lngACount) = DateSerial(lngCount, 1, 1)
lngACount = lngACount + 1
'Thanksgiving - 4th Thursday of November
lngDay = 1
lngThanks = 0
Do
If Weekday(DateSerial(lngCount, 11, lngDay)) = 5 Then
lngThanks = lngThanks + 1
End If
lngDay = lngDay + 1
Loop Until lngThanks = 4
dteHoliday(lngACount) = DateSerial(lngCount, 11, lngDay)
lngACount = lngACount + 1
'Memorial Day - Last Monday of May
lngDay = 31
Do
If Weekday(DateSerial(lngCount, 5, lngDay)) = 2 Then
dteHoliday(lngACount) = DateSerial(lngCount, 5, lngDay)
Else
lngDay = lngDay - 1
End If
Loop Until dteHoliday(lngACount) >= DateSerial(lngCount, 5, 1)
lngACount = lngACount + 1
'Labor Day - First Monday of Septemeber
lngDay = 1
Do
If Weekday(DateSerial(lngCount, 9, lngDay)) = 2 Then
dteHoliday(lngACount) = DateSerial(lngCount, 9, lngDay)
Else
lngDay = lngDay + 1
End If
Loop Until dteHoliday(lngACount) >= DateSerial(lngCount, 9, 1)
'MsgBox dteHoliday(5)
lngACount = lngACount + 1
'Easter
lngDay = (((255 - 11 * (lngCount Mod 19)) - 21) Mod 30) + 21
dteHoliday(lngACount) = DateSerial(lngCount, 3, 1) + lngDay + _
(lngDay > 48) + 6 - ((lngCount + lngCount \ 4 + _
lngDay + (lngDay > 48) + 1) Mod 7)
Next
For lngCount = 1 To DateDiff("d", dteStart, dteEnd)
dteCurr = (dteStart + lngCount)
If (Weekday(dteCurr) <> 1) And (Weekday(dteCurr) <> 7) Then
blnHol = False
For dteLoop = 0 To UBound(dteHoliday)
'MsgBox dteHoliday(dteLoop) & " " & dteLoop
If (dteHoliday(dteLoop) = dteCurr) Then
blnHol = True
End If
Next dteLoop
If blnHol = False Then
lngTotal = lngTotal + 1
'MsgBox dteCurr
End If
End If
Next lngCount
BusinessDays = lngTotal
Else 'Add
BusinessDays = -1 ' add
End If 'add
err_workingDays:
MsgBox "Error No: " & Err.Number & vbCr & _
"Description: " & Err.Description
Resume exit_workingDays
End Function
The code fails when Year(dteStartDate) > Year(dteEndDate)
You can't ReDim an array to a negative value.
When lngEYear < lngYear, lngDiff will be less than zero.
I'm not sure that this line:
If IsDate(dteStartDate) And IsDate(dteEndDate) Then 'added here begin
is necessary, since you'll get Type Mismatch errors if you try to feed other types of values into the function. In any case, you also/instead should have something like:
If dteStartDate <= dteEndDate Then
with the Else portion returning a "known bad" answer, the way your code does here:
Else 'Add
BusinessDays = -1 ' add
End If 'add
This is just an expansion of the answers already posted by Jim Anderson
and mwolfe02
. If you accept this answer/vote it up, you should also vote up theirs....
You're getting a data type mismatch because you have declared the parameters as Date type. While a Date/Time column in the database can hold a null value, a Date variable in VBA cannot. You must therefore declare the parameters as Variants, and do some type checking at the head of your function.
This means that my comment to another answer (saying that IsDate will always return true here) is misleading. Rather than deleting the meaningless IsDate check, you should make the check meaningful by changing the parameter type from Date to Variant.
Hope this helps.

MS Access 2003 - Is there a way to programmatically define the data for a chart?

So I have some VBA for taking charts built with the Form's Chart Wizard, and automatically inserting it into PowerPoint Presentation slides. I use those chart-forms as sub forms within a larger forms that has parameters the user can select to determine what is on the chart. The idea is that the user can determine the parameter, build the chart to his/her liking, and click a button and have it in a ppt slide with the company's background template, blah blah blah.....
So it works, though it is very bulky in terms of the amount of objects I have to use to accomplish this.
I use expressions such as the following:
like forms!frmMain.Month&*
to get the input values into the saved queries, which was fine when i first started, but it went over so well and they want so many options, that it is driving the number of saved queries/objects up. I need several saved forms with charts because of the number of different types of charts I need to have this be able to handle.
SO FINALLY TO MY QUESTION:
I would much rather do all this on the fly with some VBA. I know how to insert list boxes, and text boxes on a form, and I know how to use SQL in VBA to get the values I want from tables/queries using VBA, I just don't know if there is some vba I can use to set the data values of the charts from a resulting recordset:
DIM rs AS DAO.Rescordset
DIM db AS DAO.Database
DIM sql AS String
sql = "SELECT TOP 5 Count(tblMain.TransactionID) AS Total, tblMain.Location FROM
tblMain WHERE (((tblMain.Month) = """ & me.txtMonth & """ )) ORDER BY Count
(tblMain.TransactionID) DESC;"
set db = currentDB
set rs = db.OpenRecordSet(sql)
rs.movefirst
some kind of cool code in here to make this recordset
the data of chart in frmChart ("Chart01")
thanks for your help. apologies for the length of the explanation.
It is possible to change the dataset directly in vba as I have managed to do it. However the performance is not so good so I went back to filling the results to a temp table and basing the graph on that ( see my only asked stackoverflow question) however if the dataset is quite small then you can certainly make it work. I'm not in the office but if you want code I can post on Monday
EDIT: here is the old code module I used. This is the full thing but the key part you are going to be looking at is the part about opening the datasheet of the graph and then changing the value of it like this .cells(1,0)="badger".
I enevtly dumped this method and went with a temp table as in my app the graph is redraw quite a lot and I needed to go for the fastest possible method to give a "real time" feel to it but it might be just fine for your needs
Public Sub Draw_graph(strGraph_type As String)
Dim objGraph As Object
Dim objDS As Object
Dim i As Byte
On Error GoTo Error_trap
Dim lRT_actual As Long
Dim lRT_forecast As Long
Dim Start_time As Long
Dim aCell_buffer(49, 4) As Variant
Me.acxProgress_bar.Visible = True
Me.acxProgress_bar.Value = 0
Set objGraph = Me.oleCall_graph.Object
Set objDS = objGraph.Application.datasheet
Start_time = GetTime()
With objDS
.cells.Clear
Select Case strGraph_type
Case Is = "Agents"
'**************************
'** Draw the agent graph **
'**************************
.cells(1, 1) = "Start Time"
.cells(1, 2) = "Provided"
.cells(1, 3) = "Required"
.cells(1, 4) = "Actual Required"
For i = 1 To 48
.cells(i + 1, 1) = Format(DateAdd("n", (i - 1) * 15, "08:00:00"), "HHMM")
If Me.Controls("txtAgents_pro_" & i) > 0 Then
.cells(i + 1, 2) = Me.Controls("txtAgents_pro_" & i) + Me.Controls("txtAgents_add_" & i)
Else
.cells(i + 1, 2) = 0
End If
If Me.Controls("txtAgents_req_" & i) > 0 Then
.cells(i + 1, 3) = Me.Controls("txtAgents_req_" & i)
End If
If Me.Controls("txtActual_" & i) > 0 Then
.cells(i + 1, 4) = Erlang_Agents(Me.txtServiceLevel, Me.txtServiceTime, Me.Controls("txtActual_" & i) * 4, Me.txtAVHT + CLng(Nz(Me.txtDaily_AVHT_DV, 0)))
End If
'update the progress bar
If Me.acxProgress_bar.Value + 2 < 100 Then
Me.acxProgress_bar.Value = Me.acxProgress_bar.Value + 2
Else
Me.acxProgress_bar.Value = 90
End If
Next i
Case Is = "Calls"
'**************************
'** Draw the Calls graph **
'**************************
.cells(1, 1) = "Start Time"
.cells(1, 2) = "Forecast"
.cells(1, 3) = "Actual"
For i = 1 To 48
.cells(i + 1, 1) = Format(DateAdd("n", (i - 1) * 15, "08:00:00"), "HHMM")
If Me.Controls("txtForecast_" & i) > 0 Then
.cells(i + 1, 2) = Me.Controls("txtForecast_" & i)
Else
.cells(i + 1, 2) = 0
End If
If Me.Controls("txtActual_" & i) > 0 Then
.cells(i + 1, 3) = Me.Controls("txtActual_" & i)
End If
If Me.acxProgress_bar.Value + 2 < 100 Then
Me.acxProgress_bar.Value = Me.acxProgress_bar.Value + 2
Else
Me.acxProgress_bar.Value = 90
End If
Next i
Case Is = "Call Deviation"
'**************************
'** Draw the Call Deviation graph **
'**************************
.cells(1, 1) = "Start Time"
.cells(1, 2) = "Deviation"
lRT_actual = 0
lRT_forecast = 0
For i = 1 To 48
lRT_actual = lRT_actual + Me.Controls("txtActual_" & i)
lRT_forecast = lRT_forecast + Me.Controls("txtForecast_" & i)
.cells(i + 1, 1) = Format(DateAdd("n", (i - 1) * 15, "08:00:00"), "HHMM")
.cells(i + 1, 2) = lRT_actual - lRT_forecast
If Me.acxProgress_bar.Value + 2 < 100 Then
Me.acxProgress_bar.Value = Me.acxProgress_bar.Value + 2
Else
Me.acxProgress_bar.Value = 90
End If
Next i
Case Is = "Call Deviation %"
'**************************
'** Draw the Call Deviation % graph **
'**************************
.cells(1, 1) = "Start Time"
.cells(1, 2) = "Deviation"
lRT_actual = 0
lRT_forecast = 0
For i = 1 To 48
lRT_actual = lRT_actual + Me.Controls("txtActual_" & i)
lRT_forecast = lRT_forecast + Me.Controls("txtForecast_" & i)
.cells(i + 1, 1) = Format(DateAdd("n", (i - 1) * 15, "08:00:00"), "HHMM")
If lRT_forecast > 0 Then
.cells(i + 1, 2) = (lRT_actual - lRT_forecast) / lRT_forecast
End If
If Me.acxProgress_bar.Value + 2 < 100 Then
Me.acxProgress_bar.Value = Me.acxProgress_bar.Value + 2
Else
Me.acxProgress_bar.Value = 90
End If
Next i
Case Is = "SLA"
'**************************
'*** Draw the SLA graph ***
'**************************
.cells(1, 1) = "Start Time"
.cells(1, 2) = "SLA"
.cells(1, 3) = "Actual SLA"
For i = 1 To 48
.cells(i + 1, 1) = Format(DateAdd("n", (i - 1) * 15, "08:00:00"), "HHMM")
If Me.Controls("txtSLA_" & i) > 0 Then
.cells(i + 1, 2) = Me.Controls("txtSLA_" & i) / 100
Else
.cells(i + 1, 2) = 0
End If
If Me.Controls("txtActual_SLA_" & i) > 0 Then
.cells(i + 1, 3) = Me.Controls("txtActual_SLA_" & i)
End If
If Me.acxProgress_bar.Value + 2 < 100 Then
Me.acxProgress_bar.Value = Me.acxProgress_bar.Value + 2
Else
Me.acxProgress_bar.Value = 90
End If
Next i
End Select
End With
Set objDS = Nothing
Set objGraph = Nothing
Me.acxProgress_bar.Visible = False
Exit Sub
Error_trap:
DoCmd.Hourglass False
MsgBox "An error happened in sub Draw_graph, error description, " & Err.Description, vbCritical, "Tracker 3"
End Sub
One very easy way of doing this is to base the chart on a query and update the query, for example:
strSQL = "SELECT ..."
QueryName = "qryByHospital"
If IsNull(DLookup("Name", "MsysObjects", "Name='" & QueryName & "'")) Then
CurrentDb.CreateQueryDef QueryName, strSQL
Else
CurrentDb.QueryDefs(QueryName).SQL = strSQL
End If
DoCmd.OpenReport "rptChartByHospital", acViewPreview