Delete empty rows in CSV files in vbscript - vbscript

I'm trying to export CSV files and this is my code.
The Excel CSV files have some empty cells and I wanted to delete them so I added some code (which I have marked in the comments).
The program doesn't have any errors but the empty cell still there.
Hopefully, someone can tell me what's wrong.
<%Option Explicit%>
<%
Dim strConn, strScriptName,strSQL
strConn = Application("eDSNSMS")
strSQL = Request.querystring("SQL")
sub Write_CSV_From_Recordset(RS)
if RS.EOF then
exit sub
end if
dim RX
set RX = new RegExp
RX.Pattern = "\r|\n|,|"""
dim i
dim Field
dim Separator
do until RS.EOF
Separator = ""
for i = 0 to RS.Fields.Count - 1
Field = RS.Fields(i).Value & ""
if RX.Test(Field) then
Field = """" & Replace(Field, """", """""") & """"
end if
If Left(Field, 2) = "01" and InStr(Field, "-") <> 0 Then
if Len(Field) = 11 Then
Field = "6" & Field
Field = """" & Replace(Field, "-", "") & """"
else
Field = ""
end if
elseif Left(Field, 2) = "01" and InStr(Field, "-") = 0 then
if Len(Field) = 10 Then
Field = "6" & Field
else
Field = ""
end if
elseif Left(Field, 3) = "011" and InStr(Field, "-") <> 0 then
if Len(Field) = 12 Then
Field = "6" & Field
Field = """" & Replace(Field, "-", "") & """"
else
Field = ""
end if
elseif Left(Field, 3) = "011" and InStr(Field, "-") = 0 then
if Len(Field) = 11 Then
Field = "6" & Field
else
Field = ""
end if
elseif Left(Field, 2) <> "01" and IsNumeric(Field) = true then
Field = ""
elseif Left(Field, 2) <> "01" and InStr(Field, "-") <> 0 then
Field = ""
end if
Response.Write Separator & Field
Separator = ","
next
Response.Write vbNewLine
RS.MoveNext
loop
end sub
Dim objRS, objConn, objFile, objFSO, strNewContents
' Const ForReading = 1
' Const ForWriting = 2
set objConn = server.CreateObject("ADODB.Connection")
objConn.ConnectionString = strConn
objConn.Open
set objRS = server.CreateObject("ADODB.RecordSet")
objRS.Open strSQL, strConn, 0, 1
' Set objFSO = CreateObject("Scripting.FileSystemObject")
' Set objFile = objFSO.OpenTextFile("export.csv", ForReading)
' Do Until objFile.AtEndOfStream
' strLine = objFile.Readline
' strLine = Trim(strLine)
' If Len(strLine) > 0 Then
' strNewContents = strNewContents & strLine & vbCrLf
' End If
' Loop
' objFile.Close
' Set objFile = objFSO.OpenTextFile("export.csv", ForWriting,true)
' objFile.Write strNewContents
' objFile.Close
Write_CSV_From_Recordset objRS
Response.ContentType = "text/csv"
Response.AddHeader "Content-Disposition", "attachment;filename=export.csv"
%>

If you want to keep from writing empty fields to your CSV, test the field just before you write it. For example, change:
Response.Write Separator & Field
To:
If Len(Field) > 0 Then
Response.Write Separator & Field
End If
But unless all values in this specific column/field are blank, doing this is going to throw off the alignment of your CSV.

Related

Read text and match all dates in text file otherwise write value to error.txt file

The below .TXT file is read into a VBS FileSystemObject. I am trying to search for all dates that match otherwise I need to put them in a "error.txt" file. However, when I run my code below it is always placing the matches in the error.txt file and not skipping the matching dates.
Why are the dates not matching?
INPUT:
"LIRRR 1M",.412900,02/08/2016
"LIRRR 3M",.222700,02/08/2016
"LIRRR 6M",.333200,02/08/2016
"LIRRR12M",1.1333300,02/08/2016
"FEDFRRRR",.333000,02/08/2016
"CCC 1YR",.550330,02/08/2016
"5YRCMT",1.2503300,02/08/2016
"10YRCMT",1.860000,02/08/2016
Here is the code that I have written:
On error resume next
Const ForReading = 1
Dim strSearchFor
Dim MyDate, MyWeekDay
MyDate = Date ' Assign a date.
MyWeekDay = Weekday(MyDate)
If MyWeekDay = 2 then
strSearchFor =Right("0" & DatePart("m",Date), 2)&"/"&Right("0" & DatePart("d",Date-3), 2)&"/"&DatePart("yyyy",Date)
Else
strSearchFor =Right("0" & DatePart("m",Date), 2)&"/"&Right("0" & DatePart("d",Date-1), 2)&"/"&DatePart("yyyy",Date)
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\Users\Desktop\index.txt", ForReading)
do until objTextFile.AtEndOfStream
strLine = objTextFile.ReadLine()
If InStr(strLine, strSearchFor) <> 0 then
Set objFile = objFSO.CreateTextFile("C:\Users\Desktop\pass.txt")
objFile.Write "date is match"& vbCrLf
Else
Set objFile = objFSO.CreateTextFile("C:\Users\Desktop\error.txt")
objFile.Write "date is not match"& vbCrLf
End If
loop
objTextFile.Close
Why not use RegEx to get the portion of the string that appears to be the date and use the IsDate Function to validate it?
Option Explicit
Dim arrLines,i
arrLines = ReadFile("./input.txt","byline")
For i=LBound(arrLines) to UBound(arrLines)
wscript.echo FormatOutput(arrLines(i))
Next
'*********************************************
Function FormatOutput(s)
Dim re, match
Set re = New RegExp
re.Pattern = "[\d]+[\/-][\d]+[\/-][\d]+"
re.Global = True
For Each match In re.Execute(s)
if IsDate(match.value) then
FormatOutput = CDate(match.value)
Exit For
end if
Next
Set re = Nothing
End Function
'*********************************************
Function ReadFile(path,mode)
Const ForReading = 1
Dim objFSO,objFile,i,strLine
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(path,ForReading)
If mode = "byline" then
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
strLine = objFile.ReadLine
strLine = Trim(strLine)
If Len(strLine) > 0 Then
arrFileLines(i) = strLine
i = i + 1
ReadFile = arrFileLines
End If
Loop
objFile.Close
End If
If mode = "all" then
ReadFile = objFile.ReadAll
objFile.Close
End If
End Function
'*****************************************************************

Sync outlook messages with vbscript

I have a vbscript that copy's Outlook 2003 messages into a folder in msg format.
The problems are:
I am getting "path too long" errors for some *.msg . I wish to avoid these erros and I don't know how. ' On Error Resume Next is already on the script.
I am getting only inbox messages, but I want all subfolders too;
How can I extract this in *.txt and not in *.msg, in order to become lighter?
Here is my atual script. Thanks for the help!
On Error Resume Next
Dim myNameSpace
Dim ofChosenFolder
Dim myOlApp
Dim myItem
Dim objItem
Dim myFolder
Dim strSubject
Dim strName
Dim strFile
Dim strReceived
Dim strSavePath
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set myOlApp = CreateObject("Outlook.Application")
Set myNameSpace = myOlApp.GetNamespace("MAPI")
Const olFolderInbox = 6
Set ofChosenFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
strSavePath = "c:\test\" 'OBS! use a \ at the end of the path
i = 1
For each Item in ofChosenFolder.Items
Set myItem = ofChosenFolder.Items(i)
strReceived = ArrangedDate(myitem.ReceivedTime)
' strSubject = myItem.Subject
strSubject = myitem.SenderName & "_" & myitem.Subject
strName = StripIllegalChar(strSubject)
strFile = strSavePath & strReceived & "_" & strName & ".msg"
If Not Len(strfile) > 256 then
myItem.SaveAs strfile, 3
Else
wscript.echo strfile & vbcrlf & "Path and filename too long."
End If
i = i + 1
next
Function StripIllegalChar(strInput)
'***************************************************
'Simple function that removes illegal file system
'characters.
'***************************************************
Set RegX = New RegExp
RegX.pattern = "[\" & chr(34) & "\!\#\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"
RegX.IgnoreCase = True
RegX.Global = True
StripIllegalChar = RegX.Replace(strInput, "")
Set RegX = nothing
End Function
Function ArrangedDate(strDateInput)
'***************************************************
'This function re-arranges the date data in order
'for it to display in chronilogical order in a
'sorted list in the file system. It also removes
'illegal file system characters and replaces them
'with dashes.
'Example:
'Input: 2/26/2004 7:07:33 AM
'Output: 2004-02-26_AM-07-07-33
'***************************************************
Dim strFullDate
Dim strFullTime
Dim strAMPM
Dim strTime
Dim strYear
Dim strMonthDay
Dim strMonth
Dim strDay
Dim strDate
Dim strDateTime
Dim RegX
If not Left(strDateInput, 2) = "10" Then
If not Left(strDateInput, 2) = "11" Then
If not Left(strDateInput, 2) = "12" Then
strDateInput = "0" & strDateInput
End If
End If
End If
strFullDate = Left(strDateInput, 10)
If Right(strFullDate, 1) = " " Then
strFullDate = Left(strDateInput, 9)
End If
strFullTime = Replace(strDateInput,strFullDate & " ","")
If Len(strFullTime) = 10 Then
strFullTime = "0" & strFullTime
End If
strAMPM = Right(strFullTime, 2)
strTime = strAMPM & "-" & Left(strFullTime, 8)
strYear = Right(strFullDate,4)
strMonthDay = Replace(strFullDate,"/" & strYear,"")
strMonth = Left(strMonthDay, 2)
strDay = Right(strMonthDay,len(strMonthDay)-3)
If len(strDay) = 1 Then
strDay = "0" & strDay
End If
strDate = strYear & "-" & strMonth & "-" & strDay
'strDateTime = strDate & "_" & strTime
strDateTime = strDate
Set RegX = New RegExp
RegX.pattern = "[\:\/\ ]"
RegX.IgnoreCase = True
RegX.Global = True
ArrangedDate = RegX.Replace(strDateTime, "-")
Set RegX = nothing
End Function
You need to truncate the file name appropriately (strName)
Move your code that processes a folder into a sub that take fodler that takes folder as parameter and call it for ofChosenFolder as well as all of its child fodlers in the ofChosenFolder.Folders collection.
You are calling SaveAs..., 3 - 3 here is olMsg. Specify olTxt (= 0).
Off the top of my head:
Const olFolderInbox = 6
Set ofChosenFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
trSavePath = "c:\test\"
ProcessFolder ofChosenFolder, trSavePath
sub ProcessFolder(folder, path)
For each Item in folder.Items
strReceived = ArrangedDate(Item.ReceivedTime)
strSubject = Item.SenderName & "_" &Item .Subject
strName = StripIllegalChar(strSubject)
strFile = strSavePath & strReceived & "_" & strName & ".msg"
If Not Len(strfile) > 256 then
Item.SaveAs strfile, 3
Else
wscript.echo strfile & vbcrlf & "Path and filename too long."
End If
next
for each subfolder in folder.Folders
ProcessFolder(subfolder, trSavePath & subfolder.Name & "\"
next
end sub

VB script to scan latest log file for errors

I have a VB script which scans the mentioned log file for errors and sends a notification through an email.
How can I scan the latest log file in the folder? For example, Filename1.070615 (Filename1.mmddyy) is a log file. After a certain size, the logfile switches to new file with the same name but different date: Filename1.070615.
cdoSendUsingPort = 2, _
Const ForReading = 1
Dim intStartAtLine, strFileCreateddate, i, strResults, strTextToScanFor, bStartFromScratch
Dim strLastCheckedFor, strArrayToString, strSubject, strMailFrom, strMailTo
strMailto = "<Emailaddress>"
strMailFrom = "<FromAddress>"
strSubject = "Log scanner"
strSMTPServer = "x.x.x.x"
FileToRead = "D:\LOG\filename1.mmddyy"
arrTextToScanFor = Array("error","another thing")
Set WshShell = WScript.CreateObject("WScript.Shell")
searchkey = replace(replace(filetoread,":",""),"\","_")
On Error Resume Next
strLastFileCheckedCreateDate = WshShell.RegRead("HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\CreateDate")
strLastFileLastLineChecked = WshShell.RegRead("HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\LastLineChecked")
strLastCheckedFor = WshSHell.RegRead("HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\CheckForString")
iLastCheckedLine = WshSHell.RegRead("HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\LastLineChecked")
On Error GoTo 0
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
Set varFile = objFSO.GetFile(FileToRead)
arrLastCheckedForText = split(strLastCheckedFor,",")
strFileCreateDate = varfile.datecreated
strFileModifiedDate = varfile.datelastmodified
sStatus = "<li>Using mail server: " & strSMTPServer & "</li><li>Running from: " & wscript.scriptfullname & "</li>"
Set objTextFile = objFSO.OpenTextFile(FileToRead, ForReading)
objTextFile.ReadAll
iLineCount = objTextFile.Line
objTextFile.close
If strLastCheckedFor = "" Then
bStartFromScratch = true
sStatus = sStatus & "<li>First run of script against string search</li>" & vbcrlf
ElseIf ubound(arrTextToScanFor) <> ubound(arrLastCheckedForText) Then
bStartFromScratch = true
sStatus = sStatus & "<li>Count of string search criteria has changed</li>" & vbcrlf
Else
For each strItem in arrTextToScanFor
Else
bStartFromScratch = true
'MsgBox strResults
End If
If bStartFromScratch = true Then
sStatus = sStatus & "<li>String search criteria does not match prior search</li>" & vbcrlf
End If
Next
End If
If cint(iLineCount) < cint(iLastCheckedLine) Then
bStartFromScratch = true
sStatus = sStatus & "<li>Last line checked (" & iLastCheckedLine & ") is greater than total line count (" & iLineCount & ") in file</li>"
End If
If CStr(strFileCreateDate) = CStr(strLastFileCheckedCreateDate) and bStartFromScratch <> true Then
intStartAtLine = strLastFileLastLineChecked
If bStartFromScratch <> true then
sStatus = sStatus & "<li>Continuing search from line " & intStartAtLine & "</li>" & vbcrlf
End If
ElseIf strFileCreateDate <> strLastFileCheckedCreateDate or bStartFromScratch = true Then
intStartAtLine = 0
If bStartFromScratch <> true then
sStatus = sStatus & "<li>File created date has changed, starting search from line 0</li>" & vbcrlf
End If
End If
i = 0
Dim strNextLine
For each strItem in arrTextToScanFor
strArrayToString = strArrayToString & delim & strItem
delim = ","
Next
Set objTextFile = objFSO.OpenTextFile(FileToRead, ForReading)
Do While objTextFile.AtEndOfStream <> True
If i < CInt(intStartAtLine) Then
objTextFile.skipline
Else
'MsgBox i
strNextLine = objTextFile.Readline
For each strItem in arrTextToScanFor
If InStr(LCase(strNextLine),LCase(strItem)) Then
strResults = "<span style='font-family:courier-new;color:#696969'><span style='font-weight:bold;background-color:#BEF3F3'>Line " & i & ":</span> " & replace(lcase(strNextLine),lcase(strItem),"<span style='background-color:#FFFF81'>" & strItem & "</span>") & "</span><br>" & vbcrlf & strResults
bSendMail = true
End If
Next
End If
i = i + 1
Loop
objTextFile.close
Set WshShell = CreateObject("WScript.Shell")
'Let's save our settings for next time.
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\FileChecked", FileToRead, "REG_SZ"
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\CreateDate", strFileCreateDate, "REG_SZ"
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\LastLineChecked", i, "REG_SZ"
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\LastScanned", Now, "REG_SZ"
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\CheckForString",strArrayToString, "REG_SZ"
set WshShell = nothing
strFileSummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>File path:</td><td>" & FileToRead & "</td></tr>"
strFileCreateDateSummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>Created date:</td><td>" & strFileCreateDate & "</td></tr>"
strFileModifiedDateSummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>Modified date:</td><td>" & strFileModifiedDate & "</td></tr>"
strArraySummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>Text string(s):</td><td>" & strArrayToString & "</td></tr>"
strFileLineSummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>Last line checked:</td><td>" & i & "</td></tr>"
strSummary = strFileSummary & strFileCreateDateSummary & strFileModifiedDateSummary & strArraySummary & strFileLineSummary
strBodyContent = "<table style='font-family:calibri;'>" & strSummary & "</table><br><br><span style='font-size:large;'>Entries:</span><br>" & strResults & "<div style='padding-top:30px;font-size:x-small'><br><div style='font-weight:bold;font-family:calibri;color:black;'>Job Details:<ul style='font-weight:normal;font-family:calibri;color:darkgray;'>" & sStatus & "</ul></div></div>"
on error goto 0
'Send the email if need be.
If bSendMail = true Then Call sendmail(strMailFrom,strMailTo,strSubject,strBodyContent)
'------------------------------------------------------------------------
'Function EmailFile - email the warning file
'------------------------------------------------------------------------
Function SendMail(strFrom,strTo,strSubject,strMessage)
Dim iMsg, iConf, Flds
On Error GoTo 0
'// Create the CDO connections.
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
Set Flds = iConf.Fields
'// SMTP server configuration.
With Flds
.Item(cdoSendUsingMethod) = cdoSendUsingPort
'// Set the SMTP server address here.
.Item(cdoSMTPServer) = strSMTPServer
.Update
End With
'// Set the message properties.
With iMsg
Set .Configuration = iConf
.To = strMailTo
.From = strMailFrom
.Subject = strSubject
.htmlbody = strMessage
End With
'iMsg.HTMLBody = strMessage
'// Send the message.
iMsg.Send ' send the message.
If CStr(err.number) <> 0 Then
Else
End If
End Function
It would be a bit easier if your log files were named filename1.yymmdd.
Nevertheless, we can use a regex to not only verify the filename but also swap the date components to put them in our desired format!
Set re = New RegExp
re.Pattern = "^(filename1\.)(\d{2})(\d{2})(\d{2})$"
Set fso = CreateObject("Scripting.FileSystemObject")
For Each objFile In fso.GetFolder("d:\log").Files
If re.Test(objFile.Name) Then
strCompareName = re.Replace(objFile.Name, "$1$4$2$3")
If strCompareName > strLatest Then strLatest = strCompareName
End If
Next
' Switch the name back...
strLatest = re.Replace(strLatest, "$1$3$4$2")
WScript.Echo "The latest file is: " & strLatest
This line:
strCompareName = re.Replace(objFile.Name, "$1$4$2$3")
changes the format from mmddyy to yymmdd and saves it in a string for comparison.
Once we've finished our comparisons, we just need to take the latest file we found and reverse the process:
strLatest = re.Replace(strLatest, "$1$3$4$2")
to get the original filename back!

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

VB Script Error - Worked before but now not confusingly

i am getting a error
The VB file reads col1 and finds the matching image name in the directory and the renames that file to col2 it produces a report to show what images haven't been renamed and placed the ones that have in a folder called rename
i have attached the code so you can see
strDocMap = "C:\img\DocMap.xlsx"
strInputFolder = "C:\img\"
strOutputFolder = "C:\img\renamed\"
strLogFile = "C:\img\RenamingLog.txt"
strPattern = "\d{5}"
Set regExpression = New RegExp
With regExpression
.Global = True
.IgnoreCase = True
.Pattern = strPattern
End With
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Const xlUp = -4162
Const xlFormulas = -4123
Const xlPart = 2
Const xlByRows = 1
Const xlNext = 1
Set objWB = objExcel.Workbooks.Open(strDocMap, False, True)
Set objSheet = objWB.Sheets(1)
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Right(strInputFolder, 1) <> "\" Then strInputFolder = strInputFolder & "\"
If Right(strOutputFolder, 1) <> "\" Then strOutputFolder = strOutputFolder & "\"
If objFSO.FolderExists(strOutputFolder) = False Then objFSO.CreateFolder strOutputFolder
Set objLog = objFSO.CreateTextFile(strLogFile, True)
objLog.WriteLine "Script started " & Now
objLog.WriteLine "Enumerating files in folder: " & strInputFolder
objLog.WriteLine "Renaming files to folder: " & strOutputFolder
objLog.WriteLine String(80, "=")
For Each objFile In objFSO.GetFolder(strInputFolder).Files
Set colMatches = regExpression.Execute(objFile.Name)
If colMatches.Count > 0 Then
If colMatches.Count = 1 Then
For Each objMatch In colMatches
strOldNum = objMatch.Value
Set objCell = objSheet.Cells.Find(strOldNum, objSheet.Range("A1"), xlFormulas, xlPart, xlByRows, xlNext, False, False)
If Not objCell Is Nothing Then
strNewNum = objCell.Offset(0, 1).Value
If strNewNum <> "" Then
strNewPath = strOutputFolder & strNewNum & "." & objFSO.GetExtensionName(objFile.Path)
' Check if a file already exists without the appended letter
blnValid = True
If objFSO.FileExists(strNewPath) = True Then
blnValid = False
' Start at "a"
intLetter = 97
strNewPath = strOutputFolder & strNewNum & Chr(intLetter) & "." & objFSO.GetExtensionName(objFile.Path)
Do While objFSO.FileExists(strNewPath) = True
intLetter = intLetter + 1
strNewPath = strOutputFolder & strNewNum & Chr(intLetter) & "." & objFSO.GetExtensionName(objFile.Path)
If intLetter > 122 Then Exit Do
Loop
If intLetter <= 122 Then blnValid = True
End If
If blnValid = True Then
objLog.WriteLine "Renaming " & objFile.Name & " to " & Mid(strNewPath, InStrRev(strNewPath, "\") + 1)
objFSO.MoveFile objFile.Path, strNewPath
Else
objLog.WriteLine "Unable to rename " & objFile.Name & ". Letters exhausted."
End If
End If
End If
Next
Else
objLog.WriteLine objFile.Name & " contains " & colMatches.Count & " matches. Manual adjustment required."
End If
End If
Next
objLog.WriteLine String(80, "=")
objLog.WriteLine "Script finished " & Now
objWB.Close False
objExcel.Quit
objLog.Close
MsgBox "Done"
Thanks
Jack
If line 68
objLog.WriteLine objFile.Name & " contains " & colMatches.Count & " matches. Manual adjustment required."
is really the culprit, I would argue:
The objects objLog, objFile, and colMatches were used before -
acquittal
The methods .WriteLine, .Name, and .Count look good - acquittal
Concatenation (&) should work on string literals and not
null/empty/nothing elements - acquittal
By elimination: objFile.Name contains a funny letter (not
convertable to 'ASCII'). Easy check: Replace "objFile.Name" with a
string literal.
Evidence
Dim s
For Each s In Array(Empty, Null, ChrW(1234))
On Error Resume Next
goFS.CreateTextFile("tmp.txt", True).WriteLine s
WScript.Echo Err.Description
On Error GoTo 0
Next
output:
====================================
Type mismatch
Invalid procedure call or argument
====================================

Resources