Userform not displaying in VBA - json

I have this code that gets the distance between two places. It should open a Userform so I can choose between the 3 different routes but the Userform is never displayed and the value of the cell I call the function from just displays #VALUE!.
Does anyone have a solution for this? Thanks!
I used the same function earlier with only one leg of the route and that worked perfectly. but I need to be able to choose.
Option Explicit
Dim SelectedRoute As Integer
Dim httpReq As Object
Dim leg As Variant
Function TRAVELDISTANCE(origin, destination, apikey)
Dim strUrl As String
strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
Set httpReq = CreateObject("MSXML2.XMLHTTP")
With httpReq
.Open "GET", strUrl, False
.Send
End With
Dim response As String
response = httpReq.ResponseText
Dim parsed As Dictionary
Set parsed = JsonConverter.ParseJson(response)
Dim i As Integer
Dim distances(1 To 3) As Long
Dim legs As Variant
legs = parsed("routes")
For i = 1 To 3
For Each leg In legs(i)("legs")
distances(i) = distances(i) + leg("distance")("value")
Next leg
Next i
ShowRoutesForm distances
TRAVELDISTANCE = distances(SelectedRoute)
End Function
Sub ShowRoutesForm(distances As Variant)
Dim frm As Object
Set frm = CreateObject("UserForm")
With frm
.Caption = "Select a Route"
.Width = 300
.Height = 200
Dim lblRoute1 As Object
Set lblRoute1 = .Controls.Add("Forms.Label.1")
With lblRoute1
.Caption = "Route 1: " & distances(1) & " meters"
.Left = 20
.Top = 20
.Width = 250
End With
Dim lblRoute2 As Object
Set lblRoute2 = .Controls.Add("Forms.Label.1")
With lblRoute2
.Caption = "Route 2: " & distances(2) & " meters"
.Left = 20
.Top = 40
.Width = 250
End With
Dim lblRoute3 As Object
Set lblRoute3 = .Controls.Add("Forms.Label.1")
With lblRoute3
.Caption = "Route 3: " & distances(3) & " meters"
.Left = 20
.Top = 60
.Width = 250
End With
Dim cmdOK As Object
Set cmdOK = .Controls.Add("Forms.CommandButton.1")
With cmdOK
.Caption = "OK"
.Left = 20
.Top = 100
.Width = 100
.Height = 25
End With
Dim cmdCancel As Object
Set cmdCancel = .Controls.Add("Forms.CommandButton.1")
With cmdCancel
.Caption = "Cancel"
.Left = 150
.Top = 100
.Width = 100
.Height = 25
End With
On Error Resume Next
frm.Show
If Err.Number <> 0 Then
MsgBox "Error " & Err.Number & ": " & Err.Description
End If
On Error GoTo 0
End With
If frm.ModalResult = 1 Then
SelectedRoute = 1
ElseIf frm.ModalResult = 2 Then
SelectedRoute = 2
ElseIf frm.ModalResult = 3 Then
SelectedRoute = 3
Else
SelectedRoute = 0
End If
ElseIf frm.ModalResult = 2 Then
SelectedRoute = 2
ElseIf frm.ModalResult = 3 Then
SelectedRoute = 3
Else
SelectedRoute = 0
End If
Set frm = Nothing
End Sub
Private Sub cmdOK_Click()
ModalResult = 1
Unload Me
End Sub
Private Sub cmdCancel_Click()
ModalResult = 0
Unload Me
End Sub

Related

Modifying the program for parsing

There is a program that parse a certain table from the site . Works great . I want to parse another table from the site . By the tag number “table” they are the same . I am trying to use the same program , but it gives an error : Run-time error 91 in the line :
If oRow.Cells(y).Children.Length > 0 Then
New table : http://allscores.ru/soccer/fstats.php?champ=2604&team=439&team2=420&tour=110
Old table : http://allscores.ru/soccer/new_ftour.php?champ=2604&f_team=439
New table : in the attached picture
Function extractTable(Ssilka As String, book1 As Workbook, iLoop As Long)
Dim oDom As Object, oTable As Object, oRow As Object
Dim iRows As Integer, iCols As Integer
Dim x As Integer, y As Integer
Dim data()
Dim vata()
Dim tata()
Dim oHttp As Object
Dim oRegEx As Object
Dim sResponse As String
Dim oRange As Range
Dim odRange As Range
' get page
Set oHttp = CreateObject("MSXML2.XMLHTTP")
oHttp.Open "GET", Ssilka, False
oHttp.Send
' cleanup response
sResponse = StrConv(oHttp.responseBody, vbUnicode)
Set oHttp = Nothing
sResponse = Mid$(sResponse, InStr(1, sResponse, "<!DOCTYPE "))
Set oRegEx = CreateObject("vbscript.regexp")
With oRegEx
.MultiLine = True
.Global = True
.IgnoreCase = False
.Pattern = "<(script|SCRIPT)[\w\W]+?</\1>"
sResponse = .Replace(sResponse, "")
End With
Set oRegEx = Nothing
' create Document from response
Set oDom = CreateObject("htmlFile")
oDom.Write sResponse
DoEvents
' table with results, indexes starts with zero
Set oTable = oDom.getelementsbytagname("table")(3)
DoEvents
iRows = oTable.Rows.Length
iCols = oTable.Rows(1).Cells.Length
' first row and first column contain no intresting data
ReDim data(1 To iRows - 1, 1 To iCols - 1)
ReDim vata(1 To iRows - 1, 1 To iCols - 1)
ReDim tata(1 To iRows - 1, 1 To iCols - 1)
' fill in data array
For x = 1 To iRows - 1
Set oRow = oTable.Rows(x)
For y = 1 To iCols - 1
If oRow.Cells(y).Children.Length > 0 Then
data(x, y) = oRow.Cells(y).getelementsbytagname("a")(0).getattribute("href")
data(x, y) = Replace(data(x, y), "about:", "http://allscores.ru/soccer/")
vata(x, y) = oRow.Cells(y).innerText
End If
Next y
Next x
Set oRow = Nothing
Set oTable = Nothing
Set oDom = Nothing
Set oRange = book1.ActiveSheet.Cells(110, 26 + (iLoop * 21)).Resize(iRows - 1, iCols - 1)
oRange.NumberFormat = "#"
oRange.Value = data
Set odRange = book1.ActiveSheet.Cells(34, 26 + (iLoop * 21)).Resize(iRows - 1, iCols - 1)
odRange.NumberFormat = "#"
odRange.Value = vata
Set oRange = Nothing
Set odRange = Nothing
End Function
This is not particularly robust but does grab the values from the table. iLoop is not used.
Option Explicit
Public Sub test()
extractTable "http://allscores.ru/soccer/fstats.php?champ=2604&team=439&team2=420&tour=110", ThisWorkbook, 1
End Sub
Public Sub extractTable(Ssilka As String, book1 As Workbook)
Dim oDom As Object, oTable As Object
Dim oHttp As Object
Dim oRegEx As Object
Dim sResponse As String
Set oHttp = CreateObject("MSXML2.XMLHTTP")
oHttp.Open "GET", Ssilka, False
oHttp.send
sResponse = StrConv(oHttp.responseBody, vbUnicode)
Set oHttp = Nothing
sResponse = Mid$(sResponse, InStr(1, sResponse, "<!DOCTYPE "))
Set oRegEx = CreateObject("vbscript.regexp")
With oRegEx
.MultiLine = True
.Global = True
.IgnoreCase = False
.Pattern = "<(script|SCRIPT)[\w\W]+?</\1>"
sResponse = .Replace(sResponse, "")
End With
Set oRegEx = Nothing
Set oDom = CreateObject("htmlFile")
oDom.Write sResponse
Set oTable = oDom.getElementsByTagName("table")(3)
Dim b As Object, a As Object
Set b = oTable.getElementsByTagName("TR") 'DispHTMLElementCollection
Dim i As Long, y As Long
With ActiveSheet
For i = 3 To 17 '17-3 gives the 15 rows of interest. Start at 3 to avoid header and empty row.
Set a = b(i).ChildNodes
For y = 1 To a.Length - 1
.Cells(i - 2, y) = a(y).innerText
Next y
Next i
End With
End Sub

Error on Range("A1").SpecialCells(xlLastCell))

I am getting a "Method 'Range' of object '_Global' failed" error about 50% of the time I try to run the below code. Debug takes me to this line:
Set rng = xlWS.Range(Range("A1"), xlWS.Range("A1").SpecialCells(xlLastCell))
Can anyone help with this problem?? Thanks.
Private Sub Command48_Click()
'On Error Resume Next
Dim Filename As String
Dim month1 As String
Dim year1 As Integer
Dim startTime As Date
startTime = Now
Dim strDirectoryPath As String
Filename = strDirectoryPath & "\" & "QI_GAP_REPORT_2_ " & Format$(Now(), "mm-dd-yyyy") & ".xls"
DoCmd.OpenQuery "QI_GAP_REPORT_FOR_EXCEL"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "QI_GAP_REPORT_FOR_EXCEL", Filename, False, "Summary"
DoCmd.Close acQuery, "QI_GAP_REPORT_FOR_EXCEL"
'///****Format excel workbook****////
' Late binding to avoid reference:
Dim xlApp As Object 'Excel.Application
Dim xlWB As Object 'Workbook
Dim xlWS As Object 'Worksheet
Dim GetBook As String
' Create the instance of Excel that we will use to open the temp book
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Open(Filename)
Set xlWS = xlWB.Worksheets("Summary")
' Format our temp sheet
' ************************************************** *************************
xlApp.Range("A1").Select
Const xlLandscape As Long = 2
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlContext As Integer = -5002
Const xlDown As Integer = -4121
Const xlContinuous As Integer = 1
Const xlThin As Integer = 2
Const xlLastCell As Long = 11
Const xlYes As Long = 1
With xlWS
With .UsedRange
.borders.LineStyle = xlContinuous
.borders.ColorIndex = 0
.borders.TintAndShade = 0
.borders.Weight = xlThin
End With
'format header 90 degree
With .Range("i1:y1")
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 90
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
.UsedRange.Rows.RowHeight = 15
.UsedRange.Columns.AutoFit
Dim tbl As ListObject
Dim rng As Range
Set rng = xlWS.Range(Range("A1"), xlWS.Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"
tbl.ShowTotals = True

VB6 Export To CSV: How to retain zero values

How can I retain zero values when exporting a csv file, if opened on notepad it works well, but when in excel it removes the zeroes. is there a way I can convert numbers to text in the code? eg. '4.1200' = 4.12
Private Sub ExportToCSV()
Me.progCashr.Value = 25
Static iNum
Dim iRow, iCol As Integer
Dim sText As String
Dim sPath As String
iNum = FreeFile()
Me.progCashr.Value = 50
With cd
On Error GoTo errtrap
.CancelError = True
.Filter = "*.CSV|*.CSV"
.ShowSave
If FileExists(.FileName) Then
If fMessageBox("", "Overwrite File?", "Yes", "No", 0, 1, True) = 1 Then
Me.progCashr.Value = 100
Open .FileName For Output As #iNum
MsgBox ("Export Success!")
Else
Exit Sub
End If
Else
Open .FileName For Output As #iNum
End If
End With
With Grid1
For iRow = 2 To .Rows - 1
sText = ""
For iCol = 1 To .Cols - 1
sText = sText & Replace(.Cell(iRow, iCol).Text, ",", "") & ","
Next iCol
If sText <> "" Then
sText = Left$(sText, Len(sText) - 1)
Print #iNum, sText
End If
Next iRow
End With
MsgBox ("Export Success!")
Close #iNum
Exit Sub
End Sub

Split large CSV file with header into multiple CSV files for every nth row with a header

I have a large CSV file that I would like to split into multiple CSV files. I've tried numerous VBS scripts, but I cannot seem to get this.
This script does some of what I want but does not save them as CSV files:
Sub Split()
Dim rLastCell As Range
Dim rCells As Range
Dim strName As String
Dim lLoop As Long, lCopy As Long
Dim wbNew As Workbook
With ThisWorkbook.Sheets(1)
Set rLastCell = .Cells.Find(What:="*", After:=[A1], SearchDirection:=xlPrevious)
For lLoop = 1 To rLastCell.Row Step 35
lCopy = lCopy + 1
Set wbNew = Workbooks.Add
.Range(.Cells(lLoop, 1), .Cells(lLoop + 35, .Columns.Count)).EntireRow.Copy _
Destination:=wbNew.Sheets(1).Range("A1")
wbNew.Close SaveChanges:=True, Filename:="Inventory_" & lLoop + 34
Next lLoop
End With
End Sub
Added a saveas line to your code to specify the file format, you should be all set
Sub Split()
Dim rLastCell As range
Dim rCells As range
Dim strName As String
Dim lLoop As Long, lCopy As Long
Dim wbNew As Workbook
With ThisWorkbook.Sheets(1)
Set rLastCell = .Cells.Find(What:="*", After:=[A1], SearchDirection:=xlPrevious)
For lLoop = 2 To rLastCell.Row Step 35
lCopy = lCopy + 1
Set wbNew = Workbooks.Add
.Cells(1, 1).EntireRow.Copy _
Destination:=wbNew.Sheets(1).range("A1")
.range(.Cells(lLoop, 1), .Cells(lLoop + 35, .Columns.Count)).EntireRow.Copy _
Destination:=wbNew.Sheets(1).range("A2")
wbNew.SaveAs FileName:="Inventory_" & format(lLoop + 34,"0000") & ".csv", FileFormat:=xlCSV, Local:=True
wbNew.Close SaveChanges:=False
Next lLoop
End With
End Sub
Off the top of my head:
Const ForReading = 1
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
maxRows = 35
i = 0
n = 0
Set out = Nothing
Set csv = fso.OpenTextFile("C:\PATH\TO\your.csv", ForReading)
header = csv.ReadLine
Do Until csv.AtEndOfStream
If i = 0 Then
If Not out Is Nothing Then out.Close
Set out = fso.OpenTextFile("out_" & Right("00" & n, 2) & ".csv", ForWriting)
out.WriteLine(header)
n = n + 1
End If
out.WriteLine(csv.ReadLine)
i = (i + 1) Mod maxRows
Loop
csv.Close
If Not out Is Nothing Then out.Close

how to insert new row like Excel functions in MS ACCESS

I need to find a way to make grid in MS Access & insert new lines to it by code VBA only
exactly how excel behave.
Have you looked at continuous forms and datasheets?
It is very rarely a good idea to replicate spreadsheet behaviour in a database
Code InsertRows : insert row in between tow row
first Create A temporarilytable And then deal with this table like the main table
and the code is Work with me
and here the code :
Sub InsertRows()
On Error GoTo ErrorNu
Dim SQLP As String
Dim Con As New ADODB.Connection
Dim Conx As New ADODB.Connection
Dim Rst As New ADODB.Recordset
Dim Rs As New ADODB.Recordset
Dim Rsx As New ADODB.Recordset
Dim Rn As New ADODB.Recordset
Dim Rd As New ADODB.Recordset
Dim Num As Long
Dim intRows
Dim arrEmployees As Variant
Dim x As Integer, Y As Integer
Set Con = CurrentProject.Connection
Con.BeginTrans
sqlo = " select max(AutoRec)as maxa from Note_Custom "
Set Rn = Con.Execute(sqlo)
SQLP = " SELECT AutoRec, TextCOspoId, OuerM,Note"
SQLP = SQLP & " , TextBillId,NuCOspoId,dateTybe FROM Note_Custom ORDER BY AutoRec"
Rs.Open SQLP, Con, adUseClient, adOpenStatic, adCmdText
sqlo = " UPDATE Note_Custom SET TextBillId = ''"
sqlo = sqlo & " WHERE AutoRec > " & 0
Con.Execute (sqlo)
intRows = Val(Rn!maxa)
Num = 1
arrEmployees = Rs.GetRows(intRows)
Y = 0
For x = 0 To intRows - 1
If x = Val(SelTop - 1) Then
Y = 1
Rs.AddNew
Rs![AutoRec] = arrEmployees(0, x)
Rs![TextBillId] = 1
Rs.Update
End If
Rs.AddNew
Rs![AutoRec] = arrEmployees(0, x) + Y
Rs![TextCOspoId] = arrEmployees(1, x)
Rs![OuerM] = arrEmployees(2, x)
Rs![Note] = arrEmployees(3, x)
Rs![NuCOspoId] = arrEmployees(5, x)
Rs![dateTybe] = arrEmployees(6, x)
Rs![TextBillId] = 1
Rs.Update
Next x
sqlo = "DELETE * FROM Note_Custom where TextBillId = """""
Con.Execute (sqlo)
Con.CommitTrans
SelFiled = Me.SelTop
Me.Requery
sqlo = "SELECT Last(AutoRec) AS LastAuto,First(AutoRec) AS FirstAuto,Count(AutoRec) AS CountAuto FROM Note_Custom"
Set Rd = Con.Execute(sqlo)
If Me.SelTop <> AutoRec Or Rd!LastAuto <> Rd!CountAuto Then
Refix
End If
DoCmd.GoToRecord , , acGoTo, SelFiled
'Me.SelTop = SelFiled
If RecType = False Then
Forms![Ncustom]!Edite.Enabled = True
Forms![Ncustom]!Viewer1.Enabled = False
Forms![Ncustom]!DELETE.Enabled = False
End If
arrEmployees = Empty
Rs.Close
Con.Close
Set Rs = Nothing
Set Con = Nothing
Exit Sub
ErrorNu:
SelFiled = Me.SelTop
Me.Requery
Me.SelTop = SelFiled
End Sub