VB script not returning any value - datetime

Function NextMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 1, dateval)
NextMonthName = MonthName(Month(tmp))
return NextMonthName
Wscript.Echo NextMonthName
End Function
Function PrevMonthName(dateval)
Dim tmp : tmp = DateAdd("m", -1, dateval)
NextMonthName = MonthName(Month(tmp))
return NextMonthName
End Function
I am running the above mentioned VB script and it completes fine without any output. I want the result in text file. I am not able to get the output in console also.

As there is no return in VBScript, this
Option Explicit
Function NextMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 1, dateval)
NextMonthName = MonthName(Month(tmp))
return NextMonthName
End Function
WScript.Echo NextMonthName(Now)
will fail with
...\31436343.vbs(6, 5) Microsoft VBScript runtime error: Variable is undefined: 'return'
(looks like you asked a question based on code containing a global "On Error Resume Next")
Removing the offending line -
Option Explicit
Function NextMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 1, dateval)
NextMonthName = MonthName(Month(tmp))
End Function
WScript.Echo NextMonthName(Now)
solves the problem:
cscript 31436343.vbs
August

To write the ouput into text file ;
Option Explicit
Dim Title,dateval,Message
Title = "The previous Month and The Next Month"
dateval = Now()
Message = "The previous Month : "& PrevMonthName(dateval) & " "& Year(dateval) & vbCrLf &_
"The Next Month :"& NextMonthName(dateval) & " "& Year(dateval)
MsgBox Message,VbInformation,Title
WriteLog Message
'*******************************************
Function PrevMonthName(dateval)
Dim tmp : tmp = DateAdd("m", -1, dateval)
PrevMonthName = MonthName(Month(tmp))
End Function
'*******************************************
Function NextMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 1, dateval)
NextMonthName = MonthName(Month(tmp))
End Function
'*******************************************
Sub WriteLog(strText)
Dim fs,ts,LogFile
Const ForWriting = 2
LogFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "log"
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(LogFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'********************************************

Related

Called to stored procedure through VB.net application not working

I have a VB.Net application that calls the database stored procedure and it supposedly suppose to look for tasks in a table with the Status of "Wait" and then updates it to executing and then generates the report.
However, I have ran the step in Visual Studio but it seems it doesn't to run the store procedure or run the stored procedure with no result .
I have individually ran the stored procedure through SQL Developer to check it and it works, so I don't think it's the problem.
I find that the rsresult never has rows so I am wondering do I need to add another line of code after ExecuteReader?
Can you all please help?
Below is the function and stored procedure
Public Function SelectGetTasktoExec(ByVal plngCount As Integer, ByVal
pstrIPAddr As String, ByRef pdicResult As Dictionary) As Boolean
Dim result As Boolean = False
Dim blnResult As Boolean
Dim strCaller As String = ""
Dim strErrMsg As String = ""
Dim lngRet As Integer
Dim rsResult As OracleDataReader = Nothing
Dim dicItem As Dictionary
Dim intIndex As Integer
Try
m_TranObj.CreateSPCaller("PKG_TD_BATCH_REPORT.SELECT_REPRINT_TASK")
m_TranObj.AddSPParams("i_task_count", OracleDbType.Decimal, 10, plngCount, ParameterDirection.Input)
m_TranObj.AddSPParams("i_ipaddr", OracleDbType.Varchar2, 16, pstrIPAddr, ParameterDirection.Input)
m_TranObj.AddSPParams("ocs_name", OracleDbType.RefCursor, 20, Nothing, ParameterDirection.Output)
m_TranObj.AddSPParams("o_err_code", OracleDbType.Decimal, 20, lngRet, ParameterDirection.Output)
If Not m_TranObj.RunSPReturnRS(lngRet, "o_err_code", rsResult) Then
strErrMsg = "call Pkg_Td_Batch_Report.SELECT_REPRINT_TASK failed."
Throw New Exception()
End If
If lngRet <> 0 Then
strErrMsg = "Call Pkg_Td_Batch_Report.SELECT_REPRINT_TASK failed,Error code:" & CStr(lngRet)
Throw New Exception()
End If
intIndex = gc_DicFirstKey
rsResult.Read()
While rsResult.HasRows()
dicItem = New Dictionary
dicItem.Add(gc_KEY_TASK_NO, rsResult("TASK_NO") & "")
dicItem.Add(gc_KEY_QUEUE_NO, rsResult("QUEUE_NO") & "")
dicItem.Add(gc_KEY_START_DATE, rsResult("START_DATE") & "")
dicItem.Add(gc_KEY_END_DATE, rsResult("END_DATE") & "")
dicItem.Add(gc_KEY_STORAGE_PATH, rsResult("STORAGE_PATH") & "")
dicItem.Add(gc_KEY_DATA_SOURCE, rsResult("DATA_SOURCE") & "")
dicItem.Add(gc_KEY_TEMPLATE_NAME, rsResult("TEMPLATE_NAME") & "")
dicItem.Add(gc_KEY_SOFT_COPY_FORMATS, rsResult("SOFT_COPY_FORMATS") & "")
dicItem.Add(gc_KEY_SCHEDULED_EXECUTE_DATE, rsResult("SCHEDULED_EXECUTE_DATE") & "")
dicItem.Add(gc_KEY_HARD_DISTRIBUTION_IND, rsResult("PRINT_IND") & "")
dicItem.Add(gc_KEY_SOFT_DISTRIBUTION_IND, rsResult("EXPORT_IND") & "")
dicItem.Add(gc_KEY_RESULT_PATH, rsResult("RESULT_PATH") & "")
dicItem.Add(gc_KEY_PRINTER_NAME, rsResult("PRINTER_NAME") & "")
dicItem.Add(gc_KEY_TRACTOR_NO, rsResult("TRACTOR_NO") & "")
dicItem.Add(gc_KEY_TEMPLATE_NO, rsResult("TEMPLATE_NO") & "")
dicItem.Add(gc_KEY_DUPLEX_PRINT_IND, rsResult("DUPLEX_PRINT_IND") & "")
dicItem.Add(gc_KEY_DESCRIPTION, rsResult("DESCRIPTION") & "")
dicItem.Add(gc_KEY_DEPT_DIVISION_CODE, rsResult("DEPT_DIVISION_CODE") & "")
dicItem.Add(gc_KEY_SYSDATE, Strings.Format(rsResult("SYSDATE"), gc_FormatDateTime) & "")
dicItem.Add(gc_KEY_FROM_PAGE, rsResult("FROM_PAGE") & "")
dicItem.Add(gc_KEY_TO_PAGE, rsResult("TO_PAGE") & "")
'add end
pdicResult.Add(intIndex, dicItem)
intIndex += 1
End While
SBL_Error.DebugLog(strCaller, "End")
blnResult = True
Catch excep As System.Exception
blnResult = False
SBL_Error.ErrorLog(strCaller, strErrMsg & excep.ToString)
Throw excep
Finally
result = blnResult
End Try
Return result
End Function
Here is the RunSPReturnRS method:
Public Function RunSPReturnRS(ByRef plngCnt As Integer, ByVal pstrReturnName
As String, ByRef prsResult As Object) As Boolean
Dim result As Boolean = False
Dim blnResult As Boolean
Dim strCaller As String = ""
Dim strErrMsg As String = ""
Dim strMsg As String = ""
Dim rsresult As String = ""
Try
If Not mblnConnected Then
If Not Connect() Then
strErrMsg = "Can not open connection!"
End If
End If
prsResult = mCmd.ExecuteReader()
If prsResult.HasRows Then
prsResult.Read()
prsResult = prsResult(0).ToString()
strMsg = "Batch Date is" + Space(1) + prsResult
Else
prsResult = prsResult
End If
If pstrReturnName Is "" Then
plngCnt = mCmd.Parameters(pstrReturnName).Value
End If
mCmd.Dispose()
SBL_Error.DebugLog(strCaller, strMsg)
blnResult = True
Catch ex As Exception
SBL_Error.ErrorLog(strCaller, ex.ToString())
blnResult = False
Finally
result = blnResult
End Try
Return result
There's little to go on here... but... if the stored procedure only returns a single row then you'd never see the result.
You need the rsResult.Read within the While loop:
While rsResult.HasRows
rsResult.Read
' do your processing...
End While

Pass Arguments from VBS to R

I have an R-script, which runs a VBS.
VB-Script should pass arguments back to R.
I created the codes, but passed argument is still NA.
R:
path <- "C:\\Users\\PD\\Desktop\\Dashboard Citi R\\test\\scripcik.vbs"
shell(shQuote(normalizePath(path)), "cscript", flag = "//nologo")
args<-commandArgs(TRUE)
myvar<-args[1]
print(myvar)
VBS:
dim myArr
Dim shell
Set shell = CreateObject("WScript.Shell")
chartpath6 = "C:\Users\PD\Desktop\Dashboard Citi R\test\bazy\" & myDate(now) & ".accdb"
chartpath5 = "C:\Users\PD\Desktop\Dashboard Citi R\test\bazy\" & myDate(now)-1 & ".accdb"
myArr = Array(chartpath6,chartpath5)
for i = 0 to 1
ReportFileStatus(myArr(i))
next
sub ReportFileStatus(filespec)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
msgbox msg
End sub
Function myDate(dt)
dim m,y
m = right("0" & datePart("m",dt),2)
y = datePart("yyyy",dt)
myDate= y & m
End Function
Dim path
path = "Rscript C:\Users\PD\Desktop\Dashboard Citi R\test\runR.R " & msg
shell.Run(path)
If the variable you try to send is a text message, you can write it to a txt file and loop from R until value of the text file not null or empty (I nerver tried to code with R) and then use the value of the text file.
(I also tried wscript.echo "MYTEXT" and run it from command line but it poped a msgbox).

Automatically make URLs clickable with formatted url title

I use the below code to automatic create links in my strings. But how do I convert a link like:
http://stackoverflow.com/questions/ask
into:
stackoverflow.com
As it is now, the output is:
http://stackoverflow.com/questions/ask
Thanks in advance!
Function create_links(strText)
strText = " " & strText
strText = ereg_replace(strText, "(^|[\n ])([\w]+?://[^ ,""\s<]*)", "$1$2")
strText = ereg_replace(strText, "(^|[\n ])((www|ftp)\.[^ ,""\s<]*)", "$1$2")
strText = right(strText, len(strText)-1)
create_links = strText
end function
Function ereg_replace(strOriginalString, strPattern, strReplacement)
' Function replaces pattern with replacement
dim objRegExp : set objRegExp = new RegExp
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
objRegExp.Global = True
ereg_replace = objRegExp.replace(strOriginalString, strReplacement)
set objRegExp = nothing
end function
I finally solved it using the following code:
Function create_links(strText)
strText = " " & strText
strText = MakeLink(strText, "http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\#\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?")
create_links = strText
End function
Function MakeLink(txt, strPattern)
Dim re, targetString, colMatch, objMatch
Set re = New RegExp
With re
.Pattern = strPattern
.Global = True
.IgnoreCase = True
End With
Set colMatch = re.Execute(txt)
For each objMatch in colMatch
matchedValue = right(objMatch.Value, len(objMatch.Value))
if instr(matchedValue, "://") Then
Else
matchedValue = "http://" & matchedValue
End If
urlName = replace(replace(replace(matchedValue, "http://", ""), "https://", ""), "www.", "")
If instr(urlName, "/") Then
Arr = split(urlName, "/")
urlName = Arr(0)
End If
urlName = UCase(Left(urlName,1)) & LCase(Right(urlName, Len(urlName) - 1))
txt = replace(txt, objMatch.Value, " " & urlName & "")
Next
MakeLink = txt
End Function

What is a fast and efficient way to import images by URL?

Would I just use MSXML and import as binary? Or is there another more efficient way?
There are gigs and gigs of JPEGs to fetch.
I have written something in the past, the code below will save remote image on the server disk. It's classic ASP and pretty efficient:
<%
Const CONTENT_FOLDER_NAME = "StoredContents"
Dim strImageUrl
strImageUrl = "http://www.gravatar.com/avatar/8c488f9c3d3da5bb756507179a3d53fd?s=32&d=identicon&r=PG"
Call SaveOnServer(strImageUrl, "bill_avatar.jpg")
Sub SaveOnServer(url, strFileName)
Dim strRawData, objFSO, objFile
Dim strFilePath, strFolderPath, strError
strRawData = GetBinarySource(url, strError)
If Len(strError)>0 Then
Response.Write("<span style=""color: red;"">Failed to get binary source. Error:<br />" & strError & "</span>")
Else
strFolderPath = Server.MapPath(CONTENT_FOLDER_NAME)
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
If Not(objFSO.FolderExists(strFolderPath)) Then
objFSO.CreateFolder(strFolderPath)
End If
If Len(strFileName)=0 Then
strFileName = GetCleanName(url)
End If
strFilePath = Server.MapPath(CONTENT_FOLDER_NAME & "/" & strFileName)
Set objFile = objFSO.CreateTextFile(strFilePath)
objFile.Write(RSBinaryToString(strRawData))
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
Response.Write("<h3>Stored contents of " & url & ", total of <span style=""color: blue;"">" & LenB(strRawData) & "</span> bytes</h3>")
Response.Write("<a href=""" & CONTENT_FOLDER_NAME & "/" & strFileName & """ target=""_blank""><span style=""color: blue;"">" &_
strFileName & "</span></a>")
End If
End Sub
Function RSBinaryToString(xBinary)
''# Antonin Foller, http://www.motobit.com
''# RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
''# to a string (BSTR) using ADO recordset
Dim Binary
'' #MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary
Dim RS, LBinary
Const adLongVarChar = 201
Set RS = CreateObject("ADODB.Recordset")
LBinary = LenB(Binary)
If LBinary>0 Then
RS.Fields.Append "mBinary", adLongVarChar, LBinary
RS.Open
RS.AddNew
RS("mBinary").AppendChunk Binary
RS.Update
RSBinaryToString = RS("mBinary")
Else
RSBinaryToString = ""
End If
End Function
Function MultiByteToBinary(MultiByte)
''# © 2000 Antonin Foller, http://www.motobit.com
''# MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY)
''# Using recordset
Dim RS, LMultiByte, Binary
Const adLongVarBinary = 205
Set RS = CreateObject("ADODB.Recordset")
LMultiByte = LenB(MultiByte)
If LMultiByte>0 Then
RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte
RS.Open
RS.AddNew
RS("mBinary").AppendChunk MultiByte & ChrB(0)
RS.Update
Binary = RS("mBinary").GetChunk(LMultiByte)
End If
MultiByteToBinary = Binary
End Function
Function GetBinarySource(url, ByRef strError)
Dim objXML
Set objXML=Server.CreateObject("Microsoft.XMLHTTP")
GetBinarySource=""
strError = ""
On Error Resume Next
objXML.Open "GET", url, False
objXML.Send
If Err.Number<>0 Then
Err.Clear
Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXML.Open "GET", url, False
objXML.Send
If Err.Number<>0 Then
strError = "Error " & Err.Number & ": " & Err.Description
Err.Clear
Exit Function
End If
End If
On Error Goto 0
GetBinarySource=objXML.ResponseBody
Set objXML=Nothing
End Function
Function GetCleanName(s)
Dim result, x, c
Dim arrTemp
arrTemp = Split(s, "/")
If UBound(arrTemp)>0 Then
For x=0 To UBound(arrTemp)-1
result = result & GetCleanName(arrTemp(x)) & "_"
Next
result = result & GetPageName(s)
Else
For x=1 To Len(s)
c = Mid(s, x, 1)
If IsValidChar(c) Then
result = result & c
Else
result = result & "_"
End If
Next
End If
Erase arrTemp
GetCleanName = result
End Function
Function IsValidChar(c)
IsValidChar = (c >= "a" And c <= "z") Or (c >= "A" And c <= "Z") Or (IsNumeric(c))
End Function
Function GetPageName(strUrl)
If Len(strUrl)>0 Then
GetPageName=Mid(strUrl, InStrRev(strUrl, "/")+1, Len(strUrl))
Else
GetPageName=""
End If
End Function
%>
Just call SaveOnServer sub routine passing the URL and desired file name, you can also omit the file name and in that case, the file name will be taken from the URL itself.
The server folder is defined as constant and will be in the same place as .asp file.
Here is the gist of how to download and save files in script:-
Function DownloadAndSave(sourceUrl, destinationFile)
Dim req : Set req = CreateObject("WinHttp.WinHttpRequest.5.1")
req.Open "GET", sourceUrl, false
req.Send
Dim stream : Set stream = CreateObject("ADODB.Stream")
stream.Type = 1 ''# adTypeBinary
stream.Open
stream.Write req.ResponseBody
stream.SaveToFile destinationFile, 2
stream.Close
End Function

Adaptive a vba excel function to be recursive

Im having trouble converting a working solution that takes a directory folder as an input and outputs the filenames and other file attributes of files container in the folder into an excel spreadsheet to a recursive solution that also outputs the files contained in subfolders. I would greatly appreciate any help!
Sub GetFileList()
Dim strFolder As String
Dim varFileList As Variant
Dim FSO As Object, myFile As Object
Dim myResults As Variant
Dim l As Long
' Get the directory from the user
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub
'user cancelled
strFolder = .SelectedItems(1)
End With
' Get a list of all the files in this directory. ' Note that this isn't recursive... although it could be...
varFileList = fcnGetFileList(strFolder)
If Not IsArray(varFileList) Then
MsgBox "No files found.", vbInformation
Exit Sub
End If
' Now let's get all the details for these files ' and place them into an array so it's quick to dump to XL.
ReDim myResults(0 To UBound(varFileList) + 1, 0 To 5)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(0, 1) = "Size"
myResults(0, 2) = "Created"
myResults(0, 3) = "Modified"
myResults(0, 4) = "Accessed"
myResults(0, 5) = "Full path"
Set FSO = CreateObject("Scripting.FileSystemObject")
' Loop through our files
For l = 0 To UBound(varFileList)
Set myFile = FSO.GetFile(CStr(varFileList(l)))
myResults(l + 1, 0) = CStr(varFileList(l))
myResults(l + 1, 1) = myFile.Size
myResults(l + 1, 2) = myFile.DateCreated
myResults(l + 1, 3) = myFile.DateLastModified
myResults(l + 1, 4) = myFile.DateLastAccessed
myResults(l + 1, 5) = myFile.Path
Next l
' Dump these to a worksheet
fcnDumpToWorksheet myResults
'tidy up
Set myFile = Nothing
Set FSO = Nothing
End Sub
Private Function fcnGetFileList(ByVal strPath As String, Optional strFilter As String) As Variant ' Returns a one dimensional array with filenames ' Otherwise returns False
Dim f As String
Dim i As Integer
Dim FileList() As String
If strFilter = "" Then strFilter = "."
Select Case Right$(strPath, 1)
Case "\", "/"
strPath = Left$(strPath, Len(strPath) - 1)
End Select
ReDim Preserve FileList(0)
f = Dir$(strPath & "\" & strFilter)
Do While Len(f) > 0
ReDim Preserve FileList(i) As String
FileList(i) = f
i = i + 1
f = Dir$()
Loop
If FileList(0) <> Empty Then
fcnGetFileList = FileList
Else
fcnGetFileList = False
End If
End Function
Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
Dim iSheetsInNew As Integer
Dim sh As Worksheet, wb As Workbook
Dim myColumnHeaders() As String
Dim l As Long, NoOfRows As Long
If mySh Is Nothing Then
'make a workbook if we didn't get a worksheet
iSheetsInNew = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = iSheetsInNew
Set sh = wb.Sheets(1)
Else
Set mySh = sh
End If
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 1) + 1, UBound(varData, 2) + 1)) = varData
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub
I've rewritten the code to pass your results array and a counter to the recursive function. The function fills the array and calls itself with any subfolders
Sub GetFileList()
Dim strFolder As String
Dim FSO As Object
Dim fsoFolder As Object
Dim myResults As Variant
Dim lCount As Long
Set FSO = CreateObject("Scripting.FileSystemObject")
' Get the directory from the user
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub
'user cancelled
strFolder = .SelectedItems(1)
End With
Set fsoFolder = FSO.GetFolder(strFolder)
'the variable dimension has to be the second one
ReDim myResults(0 To 5, 0 To 0)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(1, 0) = "Size"
myResults(2, 0) = "Created"
myResults(3, 0) = "Modified"
myResults(4, 0) = "Accessed"
myResults(5, 0) = "Full path"
'Send the folder to the recursive function
FillFileList fsoFolder, myResults, lCount
' Dump these to a worksheet
fcnDumpToWorksheet myResults
'tidy up
Set FSO = Nothing
End Sub
Private Sub FillFileList(fsoFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim fsoFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
'load the array with all the files
For Each fsoFile In fsoFolder.Files
lCount = lCount + 1
ReDim Preserve myResults(0 To 5, 0 To lCount)
myResults(0, lCount) = fsoFile.Name
myResults(1, lCount) = fsoFile.Size
myResults(2, lCount) = fsoFile.DateCreated
myResults(3, lCount) = fsoFile.DateLastModified
myResults(4, lCount) = fsoFile.DateLastAccessed
myResults(5, lCount) = fsoFile.Path
Next fsoFile
'recursively call this function with any subfolders
Set fsoSubFolders = fsoFolder.SubFolders
For Each fsoSubFolder In fsoSubFolders
FillFileList fsoSubFolder, myResults, lCount
Next fsoSubFolder
End Sub
Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
Dim iSheetsInNew As Integer
Dim sh As Worksheet, wb As Workbook
Dim myColumnHeaders() As String
Dim l As Long, NoOfRows As Long
If mySh Is Nothing Then
'make a workbook if we didn't get a worksheet
iSheetsInNew = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = iSheetsInNew
Set sh = wb.Sheets(1)
Else
Set mySh = sh
End If
'since we switched the array dimensions, have to transpose
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
Application.WorksheetFunction.Transpose(varData)
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub

Resources