Convert Excel Cells to JSON using VBA - json

I am trying to convert Excel cells to JSON data but not able to implement correct logic.
Excel data is as follow
and excepted result is as follows
{
'pr1' : [ { 'hw' : ['LC', 'Repl']},
{ 'web' : ['LC', 'Repl']}
]
}
I have written below code but it is not working as expected.
For i = 1 To 546
If pro <> Cells(i, 1).Value Then
oFile.writeline ""
oFile.write '" + Cells(i, 1).Value + " ':{ '" + Cells(i, 2).Value + "' : ' " + Cells(i, 3).Value + "', "
Else
If pro = Cells(i, 1).Value Then
If opt1 <> Cells(i, 2).Value Then
oFile.writeline " , '" + Cells(i, 2).Value + "' : " + ",'" + Cells(i, 3).Value + "'"
Else
oFile.write '" + Cells(i, 3).Value + " ', "
oFile.write ""
End If
oFile.write " "
End If
oFile.write " "
End If
If pro = Cells(i + 1, 1).Value And opt1 <> Cells(i + 1, 2).Value Then
oFile.write " } "
End If
If pro <> Cells(i + 1, 1).Value And opt1 <> Cells(i + 1, 2).Value Then
oFile.write " "
End If
pro = Cells(i, 1).Value
opt1 = Cells(i, 2).Value
opt2 = Cells(i, 3).Value
Next i

use Dictionary object to store :
unique column A values as keys and a new dictionary as their item
for each key, the dictionary item will store column B values as unique keys and the combination of all column C values as their item
as follows:
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim key As Variant, key2 As Variant
Dim cel As Range
With Worksheets("MySheetName") ' change "MySheetName" to your actual sheet name
For Each cel In .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants)
key = cel.Value: key2 = cel.Offset(, 1).Value
If Not dict.exists(key) Then dict.Add key, CreateObject("Scripting.Dictionary")
dict(key).Item(key2) = dict(key).Item(key2) & "'" & cel.Offset(, 2).Value & "',"
Next
End With
' build the JSON string for each key (i.e. only "pr1" in your example)
Dim s As String
For Each key In dict.keys
s = String(4, " ") & "{" & vbCrLf & String(4, " ") & "'" & key & "' : [ "
For Each key2 In dict(key)
s = s & "{ '" & key2 & "' : [" & Left(dict(key)(key2), Len(dict(key)(key2)) - 1) & "]}," & vbCrLf & String(12, " ")
Next
s = Left$(s, Len(s) - 15) & vbCrLf & String(4, " ") & "]" & vbCrLf & String(3, " ") & "}"
Debug.Print s
Next

Related

Convert Excel Range to HTML-Table

Because I didn't find a proper solution, I developed an own code to convert an excel range into an html table. The result is a string and can be used within a mail for example.
The following code considers: cell dimension, font-family, -style, -size and alignment, border-style and -color (top, right, bottom, left) and interior-color
Function convertRangeToHtml(rng As Range) As String
Dim r As Range
Dim c As Range
Dim strHtml As String
strHtml = "<table style=" & Chr(34) & "border-collapse: collapse;" & Chr(34) & " > " & vbNewLine & "<tbody>"
For Each r In rng.Rows
strHtml = strHtml & vbTab & "<tr>" & vbNewLine
For Each c In r.Columns
strHtml = strHtml & vbTab & vbTab & "<td " & getCellDimension(c) & " style=" & Chr(34) & getFontStyle(c) & " " & getBorder(c) & " " & getInteriorColor(c) & Chr(34) & ">" & Trim(c.Text) & "</td>" & vbNewLine
Next c
strHtml = strHtml & vbTab & "</tr>" & vbNewLine
Next r
strHtml = strHtml & "</table>" & vbNewLine & "</tbody>"
Debug.Print strHtml
convertRangeToHtml = strHtml
End Function
Function getInteriorColor(r As Range) As String
getInteriorColor = "background-color: rgb(" & color2rgb(r.DisplayFormat.Interior.Color) & "); "
End Function
Function getBorder(r As Range) As String
Dim varBorderSytle As Variant
varBorderSytle = "border-style: "
Dim varBorderWidth As Variant
varBorderWidth = "border-width: "
Dim varBorderColor As Variant
varBorderColor = "border-color: "
For Each b In Array(8, 10, 9, 7)
Select Case r.Borders(b).LineStyle
Case -4115
varBorderSytle = varBorderSytle & "dashed "
Case -4142
varBorderSytle = varBorderSytle & "none "
Case 1
varBorderSytle = varBorderSytle & "solid "
Case -4118
varBorderSytle = varBorderSytle & "dotted "
Case Else
varBorderSytle = varBorderSytle & "solid "
End Select
Select Case r.Borders(b).Weight
Case 1
varBorderWidth = varBorderWidth & "1px "
Case -4138
varBorderWidth = varBorderWidth & "2px "
Case 4
varBorderWidth = varBorderWidth & "3px "
Case 2
varBorderWidth = varBorderWidth & "1px "
Case Else
varBorderWidth = varBorderWidth & "1px "
End Select
varBorderColor = varBorderColor & "rgb(" & color2rgb(r.Borders(b).Color) & ") "
Next b
varBorderSytle = varBorderSytle & ";"
varBorderWidth = varBorderWidth & ";"
varBorderColor = varBorderColor & ";"
getBorder = varBorderSytle & " " & varBorderWidth & " " & varBorderColor
End Function
Function getCellDimension(r As Range) As String
getCellDimension = "width=" & Chr(34) & r.Width * 96 / 72 & "" & Chr(34) & " height=" & Chr(34) & r.Height * 96 / 72 & "" & Chr(34)
End Function
Function getFontStyle(r As Range) As String
Dim varFontColor As Variant
Dim varFontName As Variant
Dim varFontStyle As Variant
Dim varFontSize As Variant
Dim varFontBold As Variant
Dim varFontItalic As Variant
Dim varTextAlign As Variant
varFontColor = "color: rgb(" & color2rgb(r.DisplayFormat.Font.Color) & "); "
varFontName = "font-family: " & r.Font.Name & "; "
varFontSize = "font-size: " & r.DisplayFormat.Font.Size & "pt; "
varFontBold = "font-weight: normal; "
If r.DisplayFormat.Font.Bold Then varFontBold = "font-weight: bold; "
varFontStyle = "font-style: normal; "
If r.DisplayFormat.Font.Italic Then varFontStyle = "font-style: italic; "
Select Case r.HorizontalAlignment
Case -4131
varTextAlign = "text-align: left; "
Case -4152
varTextAlign = "text-align: right; "
Case -4108
varTextAlign = "text-align: center; "
Case -4130
varTextAlign = "text-align: justify; "
Case 1
Select Case Application.Evaluate("TYPE(" & r.Address(0, 0, external:=True) & ")")
Case 1
varTextAlign = "text-align: right; "
Case 2
varTextAlign = "text-align: left; "
Case 4, 16
varTextAlign = "text-align: center; "
Case Else
varTextAlign = "text-align: start; "
End Select
End Select
Dim strCSS As String
strCSS = varFontColor & varFontName & varFontSize & varFontBold & varFontStyle & varTextAlign
getFontStyle = strCSS
End Function
Function color2rgb(varColor As Variant) As String
color2rgb = Format((varColor Mod 256), "00") & ", " & Format(((varColor \ 256) Mod 256), "00") & ", " & Format((varColor \ 65536), "00")
End Function
Additionally I would suggest to add a css-style wihtin the final html-file:
td {
padding:1pt 4pt 1pt 4pt;
}

Take element from a string in VB6

I have a string in this format similar to the json. Generated by the following code:
str = "{"
str &= Chr(34) & "code" & Chr(34) + ":" & Chr(34) & "0000001" & Chr(34)
str &= Chr(34) & "name" & Chr(34) + ":" & Chr(34) & "product 1" & Chr(34)
str &= Chr(34) & "value" & Chr(34) + ":" & Chr(34) & "150.00" & Chr(34)
str &= "}"
I just need to get the value after the code, name and value.
I cannot find an effective method to do this, as I will have to generalize to more terms later. How can I do this without transforming to JSON?
The code snippet you provide produces this string:
{"code":"0000001""name":"product 1""value":"150.00"}
Assuming you really are using VB6 to process this string, the following code breaks out the values:
Private Sub Test(ByVal str As String)
Dim groups As Variant
Dim values As Variant
Dim i As Integer
str = Replace(str, "{", "")
str = Replace(str, "}", "")
str = Replace(str, """""", ",")
str = Replace(str, """", "")
groups = Split(str, ",")
For i = LBound(groups) To UBound(groups)
values = Split(groups(i), ":")
Debug.Print values(1)
Next
End Sub
Something like this should help (untested):
colon% = 0
Dim completed as Boolean
while completed = false
colon% = InStr(colon% + 1, str, ":")
If colon% > 0 Then
value$ = Mid$(str, colon + 1, InStr(colon% + 2, str, Chr(34)) - colon%)
' ... do whatever with value$ here...
Else
completed = true
End If
Wend

Convert Excel Sheet (nested) to JSON

I am giving a spreedsheet and I need to convert into JSON.
I have the following spreadsheet as so:
In essence, I'd need to convert into like this:
{ "CompanyA": {
"Products": ["Beds", "Knifes", "Spoons"]
}, "CompanyB": {
"Products": ["Beds", "Knifes", "Spoons"],
"Sites": ["West Coast", "East Coast"]
}, "CompanyC": {
"Office": ["Los Angeles"]
}}
I tried looking at online sources, but I haven't got a good solution to what I am looking for
Here's some basic code which should point you to the right direction.
I have commented it as much as possible.
Sub GetJSONOutput()
Dim wks As Worksheet: Set wks = ActiveSheet
Dim lngLastRow As Long, i As Long, j As Long, k As Long
Dim blFirstRow As Boolean
Dim strOut As String
lngLastRow = wks.Cells.Find("*", wks.Cells(1, 1), , , , xlPrevious).Row
k = 1
For i = 1 To lngLastRow
'\\ First Element - Column A
'\\ Check for first line and build beginning style
If Len(wks.Cells(i, 1).Value) > 0 Then
If blFirstRow = False Then
strOut = "{ """ & wks.Cells(i, 1).Value & """: {"
blFirstRow = True
Else '\\ Rest follow the same style
strOut = "}, """ & wks.Cells(i, 1).Value & """: {"
End If
wks.Cells(k, 4).Value = strOut: k = k + 1 '--> Output Column D
End If
'\\ Middle element - Column B
If Len(wks.Cells(i, 2).Value) > 0 Then strbase = " """ & wks.Cells(i, 2).Value & """: ["
If Len(wks.Cells(i, 3).Value) > 0 Then
'\\ Now we have Middle element then we need to loop through all elements under it!
'\\ Last Element - Column C
If Len(wks.Cells(i + 1, 3).Value) > 0 Then
strAppend = ""
For j = i To wks.Cells(i, 3).End(xlDown).Row
strAppend = strAppend & "|" & wks.Cells(j, 3).Value
Next j
strOut = strbase & """" & Replace(Mid(strAppend, 2, Len(strAppend)), "|", Chr(34) & ", " & Chr(34)) & """]"
wks.Cells(k, 4).Value = strOut: k = k + 1 '--> Output Column D
i = j - 1
Else
strOut = strbase & """" & wks.Cells(i, 3).Value & """]"
wks.Cells(k, 4).Value = strOut: k = k + 1 '--> Output Column D
End If
End If
'\\ Complete output by outputting the last closing brackets
If i = lngLastRow Then
strOut = "}}"
wks.Cells(k, 4).Value = strOut '--> Output Column D
End If
Next i
End Sub
Sub ConvertToJSONText()
Dim Sht As Worksheet
Set Sht = Worksheets("Sheet1")
Dim a As Integer
Dim lstA
Dim lstB
Dim lstC
a = 0
Dim myJsonText
myJsonText = "{"
Do While True
a = a + 1
If Sht.Range("a" & a).Value = "" And Sht.Range("b" & a).Value = "" And Sht.Range("c" & a).Value = "" Then
Exit Do
End If
If Sht.Range("a" & a).Value <> "" And Sht.Range("b" & a).Value = "" And Sht.Range("c" & a).Value = "" Then
If lstB <> "" Then myJsonText = myJsonText & "]"
If lstA <> "" Then myJsonText = myJsonText & "},"
lstA = Sht.Range("a" & a).Value
lstB = ""
lstC = ""
myJsonText = myJsonText & """" & lstA & """: {"
End If
If Sht.Range("a" & a).Value = "" And Sht.Range("b" & a).Value <> "" And Sht.Range("c" & a).Value = "" Then
If lstB <> "" Then myJsonText = myJsonText & "]"
lstB = Sht.Range("B" & a).Value
lstC = ""
myJsonText = myJsonText & """" & lstB & """: ["
End If
If Sht.Range("a" & a).Value = "" And Sht.Range("b" & a).Value = "" And Sht.Range("c" & a).Value <> "" Then
If lstC <> "" Then myJsonText = myJsonText & ","
lstC = Sht.Range("C" & a).Value
myJsonText = myJsonText & """" & lstC & """"
End If
Loop
If lstB <> "" Then myJsonText = myJsonText & "]"
myJsonText = myJsonText & "}"
End Sub

Excel to JSON (with VBA) Turkish character issue

I'm converting my Excel table to Json with VBA.
But, when I look at the output Json file, the turkish characters don't look smooth.
For example,
in Excel table, "HAYRETTIN YILMAZ"
in Json, HAYRETTÝN YILMAZ
in Excel table, "HÜSEYİN DURAK"
in Json, HÜSEYÝN DURAK
How can I fix it?
You can find my VBA code below:
Sub deneme()
savename = "deneme.js"
Dim wkb As Workbook
Dim wks As Worksheet
Set wkb = ThisWorkbook
Set wks = wkb.Sheets(2)
lcolumn = wks.Cells(1, Columns.Count).End(xlToLeft).Column ' Var olan sütunun en sonu
lrow = wks.Cells(Rows.Count, "A").End(xlUp).Row ' Var olan satırın en sonu
Dim titles() As String
ReDim titles(lcolumn)
For i = 1 To lcolumn
titles(i) = wks.Cells(1, i)
Next i
wks.Columns(50).ClearContents
json = "var deneme = { " & vbCrLf
dq = """"
m = 1
For i = 2 To ActiveSheet.Range("a1048576").End(3).Row
If WorksheetFunction.CountIf(wks.Columns("a"), wks.Cells(i, 1)) = 1 Then
json = json & vbCrLf & dq & wks.Cells(i, 1) & dq & ": {" & vbCrLf
For k = 1 To lcolumn
cellvalue = wks.Cells(i, k)
json = json & dq & titles(k) & dq & ":" & dq & cellvalue & dq
If k <> lcolumn Then ' Son sütun değilse
json = json & "," & vbCrLf
ElseIf k = lcolumn Then
json = json & vbCrLf & "}," & vbCrLf
End If
Next k
'json = json & dq & wks.Cells(1, 1) & dq & ":" & dq & wks.Cells(i, 1) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 2) & dq & ":" & dq & wks.Cells(i, 2) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 3) & dq & ":" & dq & wks.Cells(i, 3) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 4) & dq & ":" & dq & wks.Cells(i, 4) & dq & vbCrLf & "}," & vbCrLf
Else
If wks.Cells(i, 50) = "" Then
For j = i To ActiveSheet.Range("a1048576").End(3).Row
If wks.Cells(j, 1) = wks.Cells(i, 1) Then
If j = i Then
json = json & dq & wks.Cells(i, 1) & dq & ": [{" & vbCrLf
For k = 1 To lcolumn
cellvalue = wks.Cells(i, k)
json = json & dq & titles(k) & dq & ":" & dq & cellvalue & dq
If k <> lcolumn Then ' Son sütun değilse
json = json & "," & vbCrLf
ElseIf k = lcolumn Then
json = json & vbCrLf & "},"
End If
Next k
'json = json & dq & wks.Cells(1, 1) & dq & ":" & dq & wks.Cells(j, 1) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 2) & dq & ":" & dq & wks.Cells(j, 2) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 3) & dq & ":" & dq & wks.Cells(j, 3) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 4) & dq & ":" & dq & wks.Cells(j, 4) & dq & vbCrLf & "},"
Else
json = json & vbCrLf & "{" & vbCrLf
For k = 1 To lcolumn
cellvalue = wks.Cells(i, k)
json = json & dq & titles(k) & dq & ":" & dq & cellvalue & dq
If k <> lcolumn Then ' Son sütun değilse
json = json & "," & vbCrLf
ElseIf k = lcolumn Then
json = json & vbCrLf & "},"
End If
Next k
'json = json & dq & wks.Cells(1, 1) & dq & ":" & dq & wks.Cells(j, 1) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 2) & dq & ":" & dq & wks.Cells(j, 2) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 3) & dq & ":" & dq & wks.Cells(j, 3) & dq & "," & vbCrLf
'json = json & dq & wks.Cells(1, 4) & dq & ":" & dq & wks.Cells(j, 4) & dq & vbCrLf & "},"
End If
wks.Cells(j, 50) = 1
End If
Next j
json = Left(json, Len(json) - 1) & "]," & vbCrLf
End If
End If
Next i
json = Left(json, Len(json) - 3) & vbCrLf & "}" & vbCrLf & "}"
myFile = "C:\Users\xxx\Desktop\" & savename
Open myFile For Output As #1
Print #1, json
Close #1
End Sub
#PeterT, I cant want to use JsonConverter, because policy of our company. Therefore, i wrote my code above. While i was using my code for Excel to Json, "HAYRETTIN YILMAZ" seems to be "HAYRETTÝN YILMAZ".
In Addition, your 3rd item was changed. "HÜSEYİN DURAK" -> "H\u00DCSEY\u0130N DURAK". JsonConverter has a same problem.
How can i fix it ?
Thanks.
I ran a test with JsonConverter and achieved the results below. Is this different than what you're getting?
Option Explicit
Sub deneme()
Dim topLevel As Dictionary
Set topLevel = New Dictionary
topLevel.Add "Item1", Cells(1, 1).Value
topLevel.Add "Item2", Cells(1, 2).Value
topLevel.Add "Item3", Cells(2, 1).Value
topLevel.Add "Item4", Cells(2, 2).Value
Dim json As String
json = ConvertToJson(JsonValue:=topLevel, Whitespace:=2)
Debug.Print json
End Sub
Generates the following JSON:
{
"Item1": "HAYRETTIN YILMAZ",
"Item2": "HAYRETT\u00DDN YILMAZ",
"Item3": "H\u00DCSEY\u0130N DURAK",
"Item4": "H\u00DCSEY\u00DDN DURAK"
}

Format DateTime to DateTime with Milliseconds

I am pulling data from database into a recordset then converting to array and then writing to a CSV.
In the database all date values are stored as timestamps in this format.
2016-05-04 08:00:00.000000
But when I write to the CSV file the timestamp does not include the milliseconds.
Anyone know how to preserve the milliseconds?
Does the data in the recordset include the milliseconds?
On Error Resume Next
Dim sPassword
Dim sUserID
Dim sDefaultLib
Dim sSystem
Dim cs
Dim rc
Dim objIEDebugWindow
sDefaultLib = *library*
sUserID = *userid*
sPassword = *password*
sSystem = *system*
cs = *connectionString*
Set con = CreateObject("ADODB.Connection")
Set data = CreateObject("ADODB.Recordset")
con.Open cs, sUserID, sPassword
rc = con.State
If (rc = 1) Then
strQuery = "SELECT * FROM Library.Table FETCH FIRST 15 ROWS ONLY FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.Open strQuery, con
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Dim theYear
Dim theMonth
Dim theDay
Dim mDate
mDate = Date()
theYear = DatePart("yyyy", mDate)
theMonth = Right(String(2, "0") & DatePart("m", mDate), 2)
theDate = Right(String(2, "0") & DatePart("d", mDate), 2)
mDate = theYear & theMonth & theDate
Set csvFile = filsSysObj.OpenTextFile("C:\SampleFile_" & mDate & ".csv", 8, True)
columnCount = data.Fields.Count
Set i = 0
For Each field In data.Fields
i= i + 1
If (i <> columnCount) Then
csvFile.Write Chr(34) & field.Name & Chr(34) & ","
Else
csvFile.Write Chr(34) & field.Name & Chr(34)
End If
Next
csvFile.Write vbNewLine
End If
rowCount = data.RecordCount
row = 0
Dim row
Dim column
Dim resultsArray
Dim dateArray
resultsArray = data.GetRows
debug "hi"
i = 0
Do Until i>5
MsgBox(i)
i = i + 1
'debug "in"
'Dim value
'Dim dArray()
'debug "in"
'value = Chr(34) & CStr(data.Fields(17).Value) & Chr(34) & ","
'dArray = additem(dArray, value)
'data.MoveNext
'dateArray = dArray
Loop
debug "out"
For row = 0 To UBound(resultsArray, 2)
For column = 0 To UBound(resultsArray, 1)
If row = UBound(resultsArray, 2) And column = UBound(resultsArray, 1) Then
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34)
Else
If column = 0 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
ElseIf column = 19 Then
csvFile.Write Chr(34) & FormatDateTime(resultsArray(column, row),4) & Chr(34) & ","
ElseIf column = 18 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
'ElseIf column = 17 Then
'csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
Else
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34) & ","
End If
End If
Next
csvFile.Write vbNewLine
Next
csvFile.close
'----------------------Helper Functions are below-----------------------------
Sub Debug(myText)
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject(objIEDebugWindow) Then
Set objIEDebugWindow = CreateObject("InternetExplorer.Application")
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
Function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
End Function
The only field I am having issues with is field 17 of the recordset.
It is a timestamp datatype from a DB2 database.
The issue was the format is a timestamp in DB2 database. When i pull into a recordset it loses the milliseconds. My solution was to modify the query to add an extra row that pulls in only milliseconds and then later concatenate that back to the date. Please see below. Thanks for everyones help.
if(rc = 1) then
logFile.write FormatDateTime(Now(), 3) & ": Database connection successful" & vbNewLine
logFile.write FormatDateTime(Now(), 3) &": Default Library: " & sDefaultLib & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": Signed into server as: " & sUserID & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": System: " & sSystem & vbNewLine
strQuery = "SELECT ws_date, groupcd, userid, firstname, lastname, clientcd, unitcd, categorycd, category, activity, wrktype, subwrktype, step_begin, step_end, report_indicator, report_indicator, count, event_dattim, key_date, key_time, key_milsec, microsecond(event_dattim) FROM *Library.Name* FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.open strQuery, con
if data.EOF then
logFile.write FormatDateTime(Now(), 3) & ": The query returned no data"
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". There was no worksteps file created. ----------------" & vbNewLine
logFile.close
end if
columnCount = data.Fields.Count
columnCount = columnCount - 1
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Set csvFile = filsSysObj.OpenTextFile("C:\VBScript\Dailys\" & fname, 8, True)
set i = 0
for each field in data.Fields
i= i + 1
if i < columnCount then
csvFile.Write chr(34) & field.name & chr(34) & ","
elseif i = columnCount then
csvFile.Write chr(34) & field.name & chr(34)
else
exit for
end if
next
csvFile.Write vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": Database connection was unsuccessful. Database Connection Return Code: " & rc
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logFile.close
csvfile.close
wscript.quit
end if
dim row
dim column
dim resultsArray
resultsArray = data.GetRows
dim arrayRows
arrayRows = ubound(resultsArray, 2)
if arrayRows <> 0 then
logFile.write FormatDateTime(Now(), 3) & ": " & (arrayRows + 1) & " rows were successfully read into the array for file " & fname & vbnewline
for row = 0 to UBound(resultsArray, 2)
for column = 0 to (UBound(resultsArray, 1) - 1)
if row = Ubound(resultsArray, 2) and column = (ubound(resultsArray, 1) - 1) then
csvFile.Write chr(34) & resultsArray(column, row) & chr(34)
else
if column = 0 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 19 then
csvFile.Write chr(34) & FormatDateTime(resultsArray(column, row),4) & chr(34) & ","
elseif column = 18 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 17 then
Dim fDate
fDate = formatDate(resultsArray(column, row)) & " " & FormatDateTime(resultsArray(column, row),4) & ":" & second(resultsArray(column,row)) & "." & resultsArray((ubound(resultsArray, 1)), row)
csvFile.Write chr(34) & fDate & chr(34) & ","
else
csvFile.Write chr(34) & resultsArray(column, row) & chr(34) & ","
end if
end if
next
csvFile.Write vbNewLine
next
logfile.write FormatDateTime(Now(), 3) & ": " & (row) & " rows have been written to " & fname &vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": There was no data in the query results array for file " & fname & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logfile.close
csvfile.close
wscript.quit
end if
csvFile.close
logfile.write "---------------- DailyWorkstepReport.vbs script successfully ended at " & Now() & "----------------" & vbNewLine
logfile.close
wscript.quit
REM ----------------------Helper Functions are below-----------------------------
Sub Debug( myText )
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject( objIEDebugWindow ) Then
Set objIEDebugWindow = CreateObject( "InternetExplorer.Application" )
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
end function