A small problem to solve in VBscript [closed] - vbscript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Can you please try this in VBScript:
You got a text file with several currency amounts, every one in one line on following format:
DESCRIPTION Date Amount
McDonalds 2011-01-01 20.00
Clothing Store 2011-01-02 30.00
Try to build a program to read that text file and sum all values found in there.

First (pedestrian) attempt:
Option Explicit
Dim goFS : Set goFS = CreateObject( "Scripting.FileSystemObject" )
Dim sFSpec : sFSpec = goFS.GetAbsolutePathName( "..\data\expenses.csv" )
WScript.Echo goFS.OpenTextFile( sFSpec ).ReadAll()
WScript.Echo "---------"
Dim tsIn : Set tsIn = goFS.OpenTextFile( sFSpec )
Dim nSum : nSum = 0.0
Dim sLine : sLine = tsIn.ReadLine()
Do Until tsIn.AtEndOfStream
sLine = tsIn.ReadLine()
Dim aFields : aFields = Split( sLine, "," )
If 2 = UBound( aFields ) Then
nSum = nSum + CDbl( aFields( 2 ) ) ' en_us, ...
' nSum = nSum + CDbl( Replace( aFields( 2 ), ".", "," ) ) ' locale de_de, ...
End If
Loop
tsIn.Close
WScript.Echo "Sum:", nSum
Output:
lineLoop - sum values (line loop)
---------------------------------------------------
"DESCRIPTION","Date","Amount"
"McDonalds",2011-01-01,20.00
"Clothing Store",2011-01-02,30.00
"paying programmer",2011-07-09,47.11
---------
Sum: 97.11
===================================================
xpl.vbs: Erfolgreich beendet. (0) [ 0,01563 secs ]
Second attempt (using a regular expression):
Dim sFSpec : sFSpec = goFS.GetAbsolutePathName( "..\data\expenses.csv" )
Dim sAll : sAll = goFS.OpenTextFile( sFSpec ).ReadAll()
WScript.Echo sAll
WScript.Echo "---------"
Dim reAmount : Set reAmount = New RegExp
reAmount.Global = True
reAmount.MultiLine = True
reAmount.Pattern = ",(\d+\.\d+)\r$"
Dim nSum : nSum = 0.0
Dim oMTS : Set oMTS = reAmount.Execute( sAll )
Dim oMT
For Each oMT In oMTS
nSum = nSum + CDbl( oMT.Submatches(0) ) ' en_us, ...
' nSum = nSum + CDbl( Replace( oMT.Submatches(0), ".", "," ) ) ' locale de_de, ...
Next
WScript.Echo "Sum:", nSum
Third attempt (ADO/Text driver):
schema.ini:
[expenses.csv]
Format=CSVDelimited
ColNameHeader=True
DateTimeFormat=YYYY-MM-DD
CharacterSet=ANSI
Col1=DESCRIPTION CHAR
Col2=Date DATE
Col3=Amount FLOAT
Code:
Const adClipString = 2
Dim sTDir : sTDir = goFS.GetAbsolutePathName( "..\data" )
Dim oTDb : Set oTDb = CreateObject( "ADODB.Connection" )
Dim sCS : sCS = Join( Array( _
"Provider=Microsoft.Jet.OLEDB.4.0" _
, "Data Source=" & sTDir _
, "Extended Properties=" & Join( Array( _
"text" _
), ";" ) _
), ";" )
oTDB.Open sCS
WScript.Echo oTDb.Execute( "SELECT * FROM [expenses.csv]" ) _
.GetString( adClipString, , vbTab, vbCrLf, "" )
WScript.Echo oTDb.Execute( "SELECT SUM(Amount) AS [Sum] FROM [expenses.csv]" ) _
.GetString( adClipString, , vbTab, vbCrLf, "" )
WScript.Echo oTDb.Execute( "SELECT SUM(Amount) AS [Sum] FROM [expenses.csv] WHERE MONTH([Date]) = 7" ) _
.GetString( adClipString, , vbTab, vbCrLf, "" )
oTDb.Close
Output:
McDonalds 01.01.2011 20
Clothing Store 02.01.2011 30
paying programmer 09.07.2011 47,11
97,11
47,11
===================================================
xpl.vbs: Erfolgreich beendet. (0) [ 0,23438 secs ]
or - with a bit of additional work:
useAdoText - sum values (ADO/Text driver)
----------------------------------------------------------------------------
----------------------------------------------------------------------------
SELECT * FROM [expenses.csv]
----------------------------------------------------------------------------
|DESCRIPTION |Date |Amount|
|McDonalds |01.01.2011| 20|
|Clothing Store |02.01.2011| 30|
|paying programmer|09.07.2011| 47,11|
----------------------------------------------------------------------------
----------------------------------------------------------------------------
SELECT SUM(Amount) AS [Sum] FROM [expenses.csv]
----------------------------------------------------------------------------
|Sum |
|97,11|
----------------------------------------------------------------------------
----------------------------------------------------------------------------
SELECT SUM(Amount) AS [Sum] FROM [expenses.csv] WHERE MONTH([Date]) = 7
----------------------------------------------------------------------------
|Sum |
|47,11|
----------------------------------------------------------------------------
============================================================================
xpl.vbs: Erfolgreich beendet. (0) [ 0,25000 secs ]

Related

How to make Natural Sort in Classic ASP? [duplicate]

I want to sort below items using natural sorting:
"Z1","Z3","Z2","Z20","Z10"
After sorting, I am expecting the order below:
"Z1","Z2","Z3","Z10","Z20"
When I tried using array list,
Set oAlist=CreateObject("System.Collections.ArrayList")
oAlist.sort
I am getting a sorting result based on ASCII:
Z1,Z10,Z2,Z20,Z3
Please help me on how to do this natural sorting using vb script
For theory see here (follow the links!). Practical demo
recordset:
Option Explicit
Const adInteger = 3 ' 00000003
Const adVarChar = 200 ' 000000C8
Dim sInp : sInp = "Z1,Z3,Z2,Z20,Z10"
Dim aInp : aInp = Split(sInp, ",")
WScript.Echo "A:", Join(aInp)
Dim oRS : Set oRS = CreateObject("ADODB.Recordset")
oRS.Fields.Append "Word", adVarChar, 50
oRS.Fields.Append "Length", adInteger
oRS.Open
Dim sWord
For Each sWord In aInp
oRS.AddNew
oRS.Fields("Word").value = Left(sWord, 1)
oRS.Fields("Length").value = CInt(Mid(sWord, 2))
oRS.UpDate
Next
oRS.Sort = "Word, Length"
Dim aTable : aTable = oRS.GetRows()
ReDim aOut(UBound(aTable, 2))
Dim i
For i = 0 To UBound(aOut)
aOut(i) = aTable(0, i) & aTable(1, i)
Next
WScript.Echo "B:", Join(aOut)
ArrayList
Option Explicit
Dim sInp : sInp = "Z1,Z3,Z2,Z20,Z10,E1,D3,C2,B20,A10"
Dim aInp : aInp = Split(sInp, ",")
WScript.Echo "A:", Join(aInp)
Dim oNAL : Set oNAL = CreateObject( "System.Collections.ArrayList" )
Dim oSB : Set oSB = CreateObject( "System.Text.StringBuilder" )
Dim sWord
For Each sWord In aInp
oSB.AppendFormat_2 "{0}{1,4}", Left(sWord, 1), CInt(Mid(sWord, 2))
sWord = oSB.ToString()
oSB.Length = 0
oNAL.Add sWord
Next
oNAL.Sort
ReDim aOut(oNAL.Count - 1)
Dim i
For i = 0 To UBound(aOut)
aOut(i) = Left(oNAL(i), 1) & CInt(Mid(oNAL(i), 2))
Next
WScript.Echo "B:", Join(aOut)

Writeline / Readline

I'm trying to get a script to read a file and display the content. However, I need to only display 5 lines per window. How can I limit the display of the file?
Set MyFile = fso.OpenTextFile(FileName, ForReading)
Do While MyFile.AtEndOfStream <> True
TextLine = MyFile.ReadLine
MsgBox TextLine,0, "Student Information"
Loop
MyFile.Close
SOLUTION:
I got the solution! Here it comes:
Set MyFile = fso.OpenTextFile(FileName, ForReading)
Do While MyFile.AtEndOfStream <> True
TextLine = textline & MyFile.ReadLine & VBCR
counter = counter + 1
if (counter mod 5 = 0) then
MsgBox TextLine,0, "Petar Moraliev"
textline = ""
end if
Loop
MsgBox TextLine,0, "Petar Moraliev"
MyFile.Close
You need an array of cnLines (e.g. 5) elements to store each range of lines from the file. If that (ring) buffer is full, do your output (e.g. MsgBox). Just be careful at the end: are there still lines in the buffer?
In code:
Option Explicit
Const cnLines = 5
Dim nUB : nUB = cnLines - 1
Dim tsIn : Set tsIn = CreateObject("Scripting.FileSystemObject").OpenTextFile(".\23117849.txt")
Dim nIdx : nIdx = nUB
ReDim aLines(nUB)
Do Until tsIn.AtEndOfStream
nIdx = (tsIn.Line - 1) Mod cnLines
aLines(nIdx) = tsIn.ReadLine()
If nIdx = nUB Then
WScript.Echo Join(aLines, " * ") ' MsgBox Join(aLines, vbCrLf)
End If
Loop
tsIn.Close
If Not nIdx = nUB Then
ReDim Preserve aLines(nIdx)
WScript.Echo Join(aLines, " * ") ' MsgBox Join(aLines, vbCrLf)
End If
output (for a file of 11 lines):
cscript 23117849.vbs
1 * 2 * 3 * 4 * 5
6 * 7 * 8 * 9 * 10
11

Looking for a way to load url in new tab and change the title once done

I am able to load url on NEW window and change the web title with the following:
Set IE = CreateObject("InternetExplorer.Application")
set WshShell = WScript.CreateObject("WScript.Shell")
IE.Navigate "http://www.google.com"
IE.Visible = True
While IE.Busy
Wend
While IE.Document.ReadyState <> "complete"
Wend
IE.Document.Title = "yoyo"
Is there any way to make it open new tab instead of new window? How?
Another senarion I am trying is with:
set WshShell = WScript.CreateObject("WScript.Shell")
url= "http://google.com/"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run(url)
IE.document.title = "yoyo"
This allow me to open new tabs on the same browser (IE) but I cannot change the page title...
Any help will be highly appreciated!
Look here:
' VB Script Document
' http://stackoverflow.com/questions/22821984/looking-for-a-way-to-load-url-in-new-tab-and-change-the-title-once-done
'
option explicit
On Error Goto 0
Dim strMyUrl : strMyUrl = "http://www.avg.com" 'strMyUrl = "http://www.jysk.cz" 'strMyUrl = "https://www.google.cz" 'strMyUrl = "www.microsoft.com"
Dim strWTitle : strWTitle = "yoyo"
Dim strResult : strResult = WScript.ScriptName '
Dim WshShell : Set WshShell = WScript.CreateObject( "WScript.Shell")
Dim IE : Set IE = Nothing
Dim oIE : Set oIE = Nothing
Dim intWExist, BrowserNavFlag, intButton, sRetVal
intWExist = FindIE( strMyUrl, oIE) 'look for MSIE window'
set IE = oIE
Select Case intWExist
Case 3
''' MSIE window found, URL match, window title match
''' (not implemented yet)
Case 2
''' MSIE window found, URL match
Case 1
''' MSIE window found, no URL match
''' BrowserNavFlag = 65536 ' navOpenNewForegroundTab
BrowserNavFlag = 2048 ' navOpenInNewTab
IE.Navigate2 strMyUrl, CLng( BrowserNavFlag), "_blank"
Case Else
''' MSIE window not found
Set IE = CreateObject( "InternetExplorer.Application")
BrowserNavFlag = 1
IE.Navigate strMyUrl ', CLng( BrowserNavFlag)
End Select
IE.Visible = True
While IE.Busy
Wscript.Sleep 100
Wend
While IE.Document.ReadyState <> "complete" 'Or IE.ReadyState <> 4
Wscript.Sleep 100
Wend
'intButton = WshShell.Popup( "watch how MSIE title change", 1)
If intWExist <> 1 Then
intWExist = 2
Else
Set oIE = Nothing
Set IE = Nothing
strResult = strResult & vbNewLine & vbTab & "FindIE() pass # 2"
Wscript.Sleep 2000 'additional time for the Navigate2 method'
intWExist = FindIE( strMyUrl, oIE) 'get right object for newly created tab'
If intWExist = 2 Then
set IE = oIE
End If
End If
If intWExist = 2 Then
IE.Document.Title = strWTitle
sRetVal = "done"
Else
sRetVal = "'IE.Document.Title = strWTitle' - not renamed"
End If
Set IE = Nothing
Wscript.Echo strResult & vbNewLine & sRetVal ' propagate result
Private Function FindIE( ByVal sUrl, ByRef oObj)
' parameters
' sUrl (input) string
' oObj (output) object
' returns
' 0 = any MSIE window not found - or found but not accessible
' 1 = a MSIE window found
' 2 = 1 and address line match
' 3 = 2 and title match (not implemented yet)
Dim ww, tpnm, tptitle, tpfulln, tpUrl, tpUrlUnencoded
Dim errNo, errStr, intLoop, intLoopLimit
Dim iFound : iFound = 0
Dim shApp : Set shApp = CreateObject( "shell.application")
With shApp
For Each ww In .windows
tpfulln = ww.FullName
strResult = strResult & vbNewLine & ww.Application & vbTab & tpfulln
If Instr( 1, Lcase( tpfulln), "iexplore.exe", 1) <> 0 Then
If iFound > 0 Then
Else
Set oObj = ww
End If
tptitle = "x x x" : tpUrl = "" : tpUrlUnencoded = ""
intLoopLimit = 100 ' to look for attributes max. intLoopLimit/10 seconds
intLoop = 0
While intLoop < intLoopLimit
intLoop = intLoop + 1
On Error Resume Next
tpnm = typename( ww.document)
errNo = Err.Number
If errNo <> 0 Then
'error if page not response (yet)'
errStr = "Error # " & CStr( errNo) & " " & Err.Description
Wscript.Sleep 100
Else
iFound = 1
intLoopLimit = intLoop ' end While..Wend loop and preserve loop counter
tptitle = ww.document.title
tpUrl = ww.document.URL
tpUrlUnencoded = ww.document.URLUnencoded
errStr = tpnm
End If
On Error Goto 0
Wend
strResult = strResult & vbTab & errStr & " " & CStr( intLoop)
If Instr( 1, Lcase( tpnm), "htmldocument", 1) <> 0 then
strResult = strResult & vbTab & tptitle _
& vbNewLine & vbTab & tpUrl _
'& vbNewLine & vbTab & tpUrlUnencoded
If Instr( 1, Lcase( tpUrl), Lcase( sUrl), 1) <> 0 Then
Set oObj = ww
iFound = 2
strResult = strResult & vbTab & "!match!"
' looking for all matching MSIE URLs
' this may take considerable time amount
' to speed up script running, uncomment next line "exit for"
' exit for
Else
End If
End If
Else
' a program reports the same shell.application property as "iexplore.exe"
' i.e. "explorer.exe"
' i.e. "HTML preview" in some editors
' etc.
End If
Next
End With
Set shApp = Nothing
strResult = strResult & vbNewLine & Cstr( iFound)
FindIE = iFound
End Function

Loop throught a description, find a string and count

I have a table with, for this example, 2 columns:
Person
Description
I need to create a result table like this:
Person Yes No Total
John 1 5 6
Laura 4 9 13
Peter 0 1 1
Total 5 15 20
The person I get it straight, but for the description I have to do a check if there is a date inside the string, Nathan Rice helped me here about it: Get a range date and search a string. One Person can have N descriptions, so I need to loop it. If the date was found in description add 1 to Yes, else add 1 to No.
CODE UPDATED
<%
varYesTotal = 0
varNoTotal = 0
Do While Not rsPerson.EOF
varYes = 0
varNo = 0
strPersonName = rsPerson("Person")
Set rsCheckYesNo = T.Execute("SELECT Description FROM Person Where Person= '" & strPersonName & "' ORDER BY Person ASC")
strDescription= rsCheckYesNo("Description")
For intDateDiff = 0 to DateDiff("d",DataInicial,DataFinal)
arrDateParts = Split(DateAdd("d",intDateDiff,DataInicial),"/")
If arrDateParts(1) <= 9 Then
arrDateParts(1) = "0" & arrDateParts(1)
End If
strCheckDate = arrDateParts(0) & "/" & arrDateParts(1) & "/" & arrDateParts(2)
Do While Not rsCheckYesNo.EOF
strDescription= rsCheckYesNo("Description")
boolDateFound = False
If InStr(strDescription, strCheckDate) > 0 Then
boolDateFound = True
varYes = varYes + 1
Else
varNo = varNo + 1
End If
rsCheckYesNo.MoveNext
Loop
Next
%>
<%
Set rsPerson= T.Execute("SELECT DISTINCT Person FROM Table")
If Not rsPerson.EOF Then
%>
<table>
<thead>
<tr>
<th>Person</th>
<th>Yes</th>
<th>No</th>
<th>Total</th>
</tr>
</thead>
<%
'We need 2 sets of counters, one set that gets set
'to zero so we can total all the records.
varYesTotal = 0
varNoTotal = 0
Do While Not rsPerson.EOF
'The other set of counters gets reset per user
'so it should be inside the users loop.
varYes = 0
varNo = 0
strPersonName = rsPerson("Person")
Set rsCheckYesNo = T.Execute("SELECT Description FROM Person Where Person= '" & strPersonName & "' ORDER BY Person ASC")
strDescription= rsCheckYesNo("Description")
Do While Not rsCheckYesNo.EOF
'Start Nathan Rice Code
boolDateFound = False
For intDateDiff = 0 to DateDiff("d",DataInicial,DataFinal)
arrDateParts = Split(DateAdd("d",intDateDiff,DataInicial),"/")
If arrDateParts(1) <= 9 Then
arrDateParts(1) = "0" & arrDateParts(1)
End If
strCheckDate = arrDateParts(0) & "/" & arrDateParts(1) & "/" & arrDateParts(2)
If InStr(strDescription, strCheckDate) > 0 Then
boolDateFound = True
varYes = varYes + 1
Exit For
Else
varNo = varNo + 1
End If
Next
'End Nathan Rice Code
rsCheckYesNo.MoveNext
Loop
%>
<tbody>
<tr>
<td><%=strPersonName%></td>
<td><%=varYes%></td>
<td><%=varNo%></td>
<td><%=(varYes + varNo)%></td>
</tr>
</tbody>
<%
varYesTotal = varYesTotal + varYes
varNoTotal = varNoTotal + varNo
rsPerson.MoveNext
Loop
rsPerson.Close
%>
<tfoot>
<tr>
<td>Total</td>
<td><%=varYesTotal%></td>
<td><%=varNoTotal%></td>
<td><%=(varYesTotal+varNoTotal)%></td>
</tr>
</tfoot>
</table>
<%
End If
%>
Your plan should look like this:
PreP for whole task
Database
Date range
Total
Print header
Get persons
For all persons
PreP for person
Get name
Get descriptions
For all descriptions
Check and count
Next
PostP for person
Compute yes/no/all (one from two)
Print row
Update total
Next
PostP for whole task
Print total
Database
Looks like your code lacks the description loop.
Update:
In code:
Option Explicit
Dim greDate : Set greDate = New RegExp
greDate.Global = True
greDate.Pattern = "(\d{2})/(\d{2})/(\d{4})" ' dd/mm/yyyy
Dim aTotal : aTotal = Array(0,0,0)
Dim aTests : aTests = Array( _
Array( "peter" _
, "In 21/02/2014 something happened") _
, Array( "paul" _
, "pi 19/02/2014 pa 26/02/2014 po" _
, "In 21/02/2013 something happened") _
, Array( "mary" _
, "pi 19/02/2014 pu 20/02/2014 25/02/2014 26/02/2014 po" _
, "pi 19/02/2014 pu 20/02/2014 ") _
)
Dim aPers
Dim dtFrom : dtFrom = #2/20/2014#
Dim dtTo : dtTo = #2/25/2014#
For Each aPers In aTests
WScript.Echo "#####", aPers(0)
Dim aPSum : aPSum = Array(0, 0, 0)
Dim nDescr
For nDescr = 1 To UBound(aPers)
Dim sTest : sTest = aPers(nDescr)
WScript.Echo "-----", qq(sTest)
Dim aDates : aDates = getDatesFrom(sTest, dtFrom, dtTo)
If -1 = UBound(aDates) Then
WScript.Echo " no interesting dates found."
aPSum(1) = aPSum(1) + 1
Else
WScript.Echo " found (m/d/yyyy!)", Join(aDates, ", ")
aPSum(0) = aPSum(0) + 1
End If
Next
aPSum(2) = aPSum(0) + aPSum(1)
WScript.Echo "*****", Join(aPSum)
Dim i
For i = 0 To UBound(aTotal) : aTotal(i) = aTotal(i) + aPSum(i) : Next
Next
WScript.Echo "#####", Join(aTotal)
Function getDatesFrom(sText, dtFrom, dtTo)
ReDim aTmp(-1)
Dim oMTS : Set oMTS = greDate.Execute(sText)
Dim oMT, dtFound
For Each oMT In oMTS
' dd/mm/yyyy
dtFound = DateSerial(CInt(oMT.SubMatches(2)), cInt(oMT.SubMatches(1)), CInt(oMT.SubMatches(0)))
If dtFound >= dtFrom And dtFound <= dtTo Then
ReDim Preserve aTmp(Ubound(aTmp) + 1)
aTmp(Ubound(aTmp)) = dtFound
End If
Next
getDatesFrom = aTmp
End Function
Function qq(s) : qq = """" & s & """" : End Function
output:
cscript 21994835-2.vbs
##### peter
----- "In 21/02/2014 something happened"
found (m/d/yyyy!) 2/21/2014
***** 1 0 1
##### paul
----- "pi 19/02/2014 pa 26/02/2014 po"
no interesting dates found.
----- "In 21/02/2013 something happened"
no interesting dates found.
***** 0 2 2
##### mary
----- "pi 19/02/2014 pu 20/02/2014 25/02/2014 26/02/2014 po"
found (m/d/yyyy!) 2/20/2014, 2/25/2014
----- "pi 19/02/2014 pu 20/02/2014 "
found (m/d/yyyy!) 2/20/2014
***** 2 0 2
##### 3 2 5

Convert Latitude/Longitude to decimal degrees

i need to convert a large txt file with latitudes, and a large txt file with longitudes into decimal degrees.
The data i have is in the current format:
7d44'31.495"W for longitude
and
41d3'40.313"N for latitude
i need to convert both of this files to decimal degrees (using a script preferably). How can i do this?
Knowing nothing about *itudes, I can only give you a general idea about how
to solve your problem:
Use a RegExp to cut the numbers from your data and feed them in a trusted formula
To give you some confidence in my proposal, I show you, how I would tackle
the two sub-problems of your task.
(1) Apply a RegExp on an input string and calculate.
Based on this section
Conversion from DMS to Decimal Degree
Given a DMS (Degrees, Minutes, Seconds) coordinate such as W87°43'41",
convert it to a number of decimal degrees using the following method:
Calculate the total number of seconds:
43'41" = (43*60 + 41) = 2621 seconds.
The fractional part is total number of seconds divided by 3600:
2621 / 3600 = ~0.728056
Add fractional degrees to whole degrees to produce the final result:
87 + 0.728056 = 87.728056
Since it is a West longitude coordinate, negate the result.
The final result is -87.728056.
found here
Code:
Dim oFmt : Set oFmt = New cFormat
Dim oRE : Set oRE = New RegExp
' 0 1 2 3
oRE.Pattern = "^([W])(\d+)°(\d+)'(\d+)""$"
Dim aTests : aTests = Array( _
Array("W87°43'41""", -87.728056) _
)
Dim aTest
For Each aTest In aTests
Dim sInp : sInp = aTest(0)
Dim nExp : nExp = aTest(1)
Dim oMTS : Set oMTS = oRE.Execute(sInp)
Dim sMsg
If 1 <> oMTS.Count Then
sMsg = oFmt.formatTwo("|{0}| didn't match /{1}/", sInp, oRE.Pattern)
Else
Dim sLoLa : sLoLa = oMTS(0).SubMatches(0)
Dim nDegrees : nDegrees = CDbl(oMTS(0).SubMatches(1))
Dim nMinutes : nMinutes = CDbl(oMTS(0).SubMatches(2))
Dim nSeconds : nSeconds = CDbl(oMTS(0).SubMatches(3))
Dim nRes
' Calculate the total number of seconds:
' 43'41" = (43*60 + 41) = 2621 seconds.
nRes = nMinutes * 60 + nSeconds
' WScript.Echo "***", nRes
' The fractional part is total number of seconds divided by 3600:
' 2621 / 3600 = ~0.728056
nRes = nRes / 3600
' WScript.Echo "***", nRes
' Add fractional degrees to whole degrees to produce the final result:
' 87 + 0.728056 = 87.728056
nRes = nDegrees + nRes
' WScript.Echo "***", nRes
' Since it is a West longitude coordinate, negate the result.
' The final result is -87.728056.
Select Case sLoLa
Case "W"
nRes = -nRes
End Select
sMsg = oFmt.formatArray(_
"{0,-12}: R: {1,12:N6} E: {2,12:N6} D: {3,12:N6}" _
, Array(sInp, nRes, nExp, nRes - nExp) _
)
End If
WScript.Echo sMsg
Next
Output:
Step00 - conversion a la wikipedia
================================================================
W87°43'41" : R: -87,728056 E: -87,728056 D: 0,000000
================================================================
xpl.vbs: Erfolgreich beendet. (0) [0.08594 secs]
Starting from an input sample, I derive (a first attempt at) the Regexp
pattern
" W 87 ° 43 ' 41 "" "
' 0 1 2 3
oRE.Pattern = "^([W])(\d+)°(\d+)'(\d+)""$"
For your data, something like this
" 7 d 44 ' 31.495 "" W "
" 41 d 3 ' 40.313 "" N "
' 0 1 2 3
oRE.Pattern = "^(\d+)d(\d+)'(\d+\.\d+)""([WN])$"
may be appropriate.
To get the parts captured by the RegExps group ()s, I access and convert
the match's submatches
Dim sLoLa : sLoLa = oMTS(0).SubMatches(0)
Dim nDegrees : nDegrees = CDbl(oMTS(0).SubMatches(1))
Dim nMinutes : nMinutes = CDbl(oMTS(0).SubMatches(2))
Dim nSeconds : nSeconds = CDbl(oMTS(0).SubMatches(3))
Then it's just computing according to the algorithm/formulas stolen
from Wikipedia (see the code/comments).
(2) Get the data from your files
If the files are not to big, you can .ReadAll() them into memory and
apply the RegExp in multiline mode:
Dim oFmt : Set oFmt = New cFormat
Dim oRE : Set oRE = New RegExp
oRE.Global = True
oRE.Multiline = True
' 0 1 2 3
oRE.Pattern = "^(\d+)d(\d+)'(\d+\.\d+)""([WN])$"
Dim sAll : sAll = goFS.OpenTextFile("..\data\f00.txt").ReadAll()
WScript.Echo sAll
WScript.Echo oFmt.formatArray( _
"|{0,-5}|{1,-11}|{2,-11}|{3,-15}|" _
, Array("LoLa", "Degrees", "Minutes", "Seconds") _
)
Dim oMTS : Set oMTS = oRE.Execute(sAll)
Dim oMT
For Each oMT In oMTS
Dim sLoLa : sLoLa = oMT.SubMatches(3)
Dim nDegrees : nDegrees = CDbl(oMT.SubMatches(0))
Dim nMinutes : nMinutes = CDbl(oMT.SubMatches(1))
Dim nSeconds : nSeconds = CDbl(oMT.SubMatches(2))
WScript.Echo oFmt.formatArray( _
"|{0,-5}|{1,11:N2}|{2,11:N2}|{3,15:N6}|" _
, Array(sLoLa, nDegrees, nMinutes, nSeconds) _
)
Next
output:
======================================================
7d44'31.495"W
41d3'40.313"N
|LoLa |Degrees |Minutes |Seconds |
|W | 7,00| 44,00| 31,495000|
|N | 41,00| 3,00| 40,313000|
======================================================
Get the cFormat class from here

Resources