cannot execute something from variable vbscript - html

the data of C:\highlight2.txt is :
"document.all.status1.innerText = 'component failure'"
<script>
set oFile=oFSO.OpenTextFile("C:\highlight2.txt",1)
text=oFile.ReadAll
oFile.Close
arrLines = Split(text, vbCrLf)
dim cmds
For Each strLine in arrLines
if strLine = "" Then
else
strLine
end if
next
</script>
<input value="component check progress" type="text" id="Status1" >
i need to change input field from text, but its not work, input text id was variable. thanks, the help i really appreciate it.

If you have a string containing code to execute, you need to execute it:
>> For Each s In Split("WScript.Echo 1|WScript.Echo 2", "|")
>> WScript.Echo "Statement:", s
>> Execute s
>> On Error Resume Next
>> s
>> WScript.Echo Err.Description
>> On Error GoTo 0
>> WScript.Echo "-----------"
>> Next
>>
Statement: WScript.Echo 1
1
Type mismatch
-----------
Statement: WScript.Echo 2
2
Type mismatch
-----------
>>

Related

Handling repeating return values, with individual messages

I have this code which works perfect for me, when running just one objShell.Run line.
Set objShell = WScript.CreateObject("WScript.Shell")
retval = objShell.Run ("cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L",1,True)
If retval < 0 Then
MsgBox "cmd aborted, return value is: " & retval
ElseIf retval > 7 Then
MsgBox "robocopy error, return value is: " & retval
Else
MsgBox "robocopy successful, return value is: " & retval
End If
How would I need to go, when I want to have multiple objShell.Run lines?
E.g.
retval = objShell.Run ("cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L",1,True)
retval = objShell.Run ("cmd /c title Phase 2 & robocopy C:\thistoo C:\thattoo /MIR /L",1,True)
retval = objShell.Run ("cmd /c title Phase 3 & robocopy C:\andthis C:\andthat /MIR /L",1,True)
I could make each retval variable unique e.g. retval1, retval2, retval3
And iterate the [If..Then..Else] statement, but that feels clunky and probably not the nicest way to go.
For me the best way would be a MsgBox showing a "report" about each individual objShell.Run line, when they are finished. Except when all lines are successful, then a MsgBox "all done" will do just fine.
In which direction do I need to start my search? Functions, arrays?
I've never used that object WScript.Shell,
but having had a look at your code, sample and explanation.
I think this is what you mean?
'-> Initialise
SequenceSteps = 3
Result = ""
ErrString = ""
MyCommandSequence(0) = "cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L"
MyCommandSequence(1) = "cmd /c title Phase 2 & robocopy C:\thistoo C:\thattoo /MIR /L"
MyCommandSequence(2) = "cmd /c title Phase 3 & robocopy C:\andthis C:\andthat /MIR /L"
'-> Process
ErrorOccurred = False
For Counta = 0 To SequenceSteps - 1
Set objShell = WScript.CreateObject("WScript.Shell")
retval = objShell.Run (MyCommandSequence(Counta), 1, True)
'-> process request result
If retval < 0 Then
ErrString = "cmd aborted, return value is: " & retval
'** NEW CODE LINE **
Exit For
ElseIf retval > 7 Then
ErrString = "robocopy error, return value is: " & retval
'** NEW CODE LINE **
Exit For
Else
Result = Result & "robocopy successful, return value is: " & retval & vbcrlf
End If
Next
'-> Display Accordingly
If Trim(ErrString) <> "" Then
MsgBox Result & vbcrlf & ErrString
Else
MsgBox "All Done"
End if
UPDATE
Re-Edited code

VBScript to output that outputs an HTML table

I am attempting to read a text file that contains rows and then output them in the form of columns in an html file. I have no problem having this work when using WScript.echo to display it on the screen, but I am unable to get it to a table in an HTML file. I am getting the following error when attempting to run the vbs file: Type mismatch: 'OpenTextFile'. Any guidance would be much appreciated
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim OutputHTML : Set OutputHTML = fso.CreateTextFile("C:\Users\Istaley.RXDATA\Desktop\NewEmployeeTest\Part2_TableData.html")
Dim file : Set file = fso.OpenTextFile("C:\Users\Istaley.RXDATA\Desktop\NewEmployeeTest\Part2_data.txt", 1, True)
Dim fc : fc = file.ReadAll : file.close : Dim fcArray : fcArray = Split(fc, vbCrLf)
OutputHTML.WriteLine "<html>"
OutputHTML.Writeline "<body>"
OutputHTML.WriteLine "<table BORDER=1>"
Dim opArray() : ReDim opArray(0)
For Each row In fcArray
Dim tmp: tmp = Split(row, "|")
For ent=0 To UBound(tmp)
If ent > UBound(opArray) Then
ReDim Preserve opArray(UBound(opArray)+1)
opArray(ent) = Trim(tmp(ent))
Else
If Len(opArray(ent)) > 0 Then
OutputHTML.WriteLine "<tr>"
opArray(ent) = opArray(ent) & " " & Trim(tmp(ent))
OutputHTML.WriteLine "</tr>"
Else
opArray(ent) = Trim(tmp(ent))
End If
End If
Next
Next
WScript.echo Join(opArray, vbCrLf)
OutputHTML.WriteLine "</table>"
OutputHTML.WriteLine "</body>"
OutputHTML.WriteLine "</html>"
OutputHTML.Write Join(opArray, vbCrLf) : OutputHTML.Close
I know it's an old topic, but this might be useful to anyone looking to do the same, like I did. It's a bit rushed, but I've added comments inline. Bits have been taken from a number of locations, so it's not all my own work...
Function LoadFile(File)
On Error Resume Next
'Declaire all variables
Dim fso,F,ReadText,strError
Dim ReadArray
Dim ReadHTMLOutput, ReadRowCount, ReadRowItem, ReadRowItemSplit, ReadElementCount, ReadElementItem
'Create the object to read files
Set fso = CreateObject("Scripting.FileSystemObject")
'Set the file to read and the format
Set F = fso.OpenTextFile(File,1)
'If there's a problem, say so...
If Err.Number <> 0 Then
strError = "<center><b><font color=Red>The file "& File &" dosen't exists !</font></b></center>"
OutputTable.InnerHTML = strError
Exit Function
End If
'Read the contents of the file into ReadText
ReadText = F.ReadAll
'Split the text based on Carriage return / Line feed
ReadArray = Split(ReadText,vbCrLf)
'fill the output variable with the HTML of the start of the table
ReadHTMLOutput = "<table border=" & chr(34) & "2" & chr(34) & ">" & vbcrlf
'starting at 0 until the last line in the array, run through each line
For ReadRowCount=0 to UBound(ReadArray)
'Take the whole row into it's own variable
ReadRowItem = ReadArray(ReadRowCount)
'Split the row (separated by commas) into an array
ReadRowItemSplit = Split(ReadRowItem,",")
'Add the HTML for the row of the table
ReadHTMLOutput = ReadHTMLOutput & "<tr>" & vbcrlf
'starting at 0 until the last entry of the row array, run through each element
For ReadElementCount=0 to UBound(ReadRowItemSplit)
'Read the element into a variable
ReadElementItem = ReadRowItemSplit(ReadElementCount)
'If the element is blank, put a space in (stops the cell being formatted empty)
If ReadElementItem = "" Then ReadElementItem = " "
'Add the HTML for the cell of the row of the table
ReadHTMLOutput = ReadHTMLOutput & "<td>" & ReadElementItem & "</td>" & vbcrlf
'Go to the next element in the row
Next
'Add the HTML for the end of the row of the table
ReadHTMLOutput = ReadHTMLOutput & "</tr>" & vbcrlf
'Go to the next row in the file
Next
'Add the HTML for the end of the table
ReadHTMLOutput = ReadHTMLOutput & "</table>" & vbcrlf
'Fill the DIV with the contents of the variable
OutputTable.InnerHTML = ReadHTMLOutput
End Function
and in the HTML:
<div id="OutputTable"></div>
That way, the DIV is filled with the HTML from ReadHTMLOutput
The issue is this line.. The first argument of OpenTextFile takes a string, but you have passed it an Object. You've already opened the text file for writing using CreateTextFile.
Set WriteOutput = fso.OpenTextFile(OutputHTML, 8, True)
Get rid of this line and change all remaining instances of WriteOutput to OutputHTML.

VBS script wont enter loop

My script will not enter either of the For loops, I have been using MsgBox to help check and it seems that it just skips over the entire loop without entering it.
"<<<" indicates where issue starts
'==========================================================
Sub Read
'======================================================
'Read Row
RR = 6
PC = 25
at this point the script is supposed to enter a loop which cycles through documents and files to read and store data
MsgBox "front For" <<<
For Cx = 1 to Cint(vTFileC)
MsgBox "in loop 1"
Cxx = 1
'Setting Target
Target = CStr(FullPath & "\" & vTFolder & "\"& vTFile & Cx &".html")
For x = Cxx to PC
MsgBox "in loop 2"
'Sets Book 1
set oBook1 = oExcel.Workbooks.Open(Target)
'Reading Table
set Stock = oExcel.Cells(RR,5)
set ID = oExcel.Cells(RR,3)
'Displays Info
MsgBox ( Cx &"/"& vTFileC &" RR: "& RR & " ID: " & ID & " Stock: " & Stock )
'Closes Book 1
oBook1.Close
MsgBox "3"
call Find_Write_Row
r = r + 1
Cxx = Cxx + 1
RR = RR + 1
Next
'to cycle to next document
Cx = Cx + 1
Next
This is where the script continues, jumping everything between here and the last section of non-code.
MsgBox "End"
'Quitting
oExcel.Quit
End Sub
'==========================================================
This is causing my script to run and then instantly close without doing anything.
This is the section of my script which sets some of the values being used
'==========================================================
' HTML INPUTS
'======================================================
'Sets Target folder from HTML input
set oTFolder = document.getElementById("Folder_")
vTFolder = oTFolder.value
'Sets Target file from HTML input
set oTFile = document.getElementById("File_")
vTFile = oTFile.value
'Sets file count from HTML input
set oTFileC = document.getElementById("C_")
vTFileC = oTFileC.value
'Toggles visibility of excel
set oVT = document.getElementById("VT")
vVT = oVT.value
'==========================================================
If For Cx = 1 to Cint(vTFileC) does not enter the loop, then Cint(vTFileC) evaluates to something that is less than 1. So vTFileC needs to be examined:
>> MsgBox TypeName(vTFileC)
>> MsgBox vTFileC
>> MsgBox CInt(vTFileC)

How to obtain last three lines content of a log file using VBScript function

Can anyone suggest me a VBscript function to get the last 3 lines of a text document (for eg: log.txt ? Below is my code which can fetch and display the entire log on my screen but I want to get only last 3 lines of the log file named log.txt.
<script type="text/Vbscript">
Option Explicit
Dim File
File = "C:\\test.txt"
'***********************************************************
Sub LoadMyFile()
myDiv.innerHTML = LoadFile(File)
End Sub
'***********************************************************
Function LoadFile(File)
On Error Resume Next
Dim fso,F,ReadMe,Tab,i,paragraphe
Set fso = CreateObject("Scripting.FileSystemObject")
Set F = fso.OpenTextFile(File,1)
LoadFile = Err.Number
If Err.Number <> 0 Then
MsgBox Err.Description,16," Error"
Exit Function
End If
ReadMe = F.ReadAll
Tab = split(ReadMe,vbcrlf)
For i = lbound(Tab) to ubound(Tab)
paragraphe=paragraphe & Tab(i) & "<br>"
Next
LoadFile = paragraphe
End Function
</script>
Code not working#Steve
<html>
<script type="text/Vbscript">
Option Explicit
Dim File
File = "C:\\test.txt"
'***********************************************************
Sub LoadMyFile()
myDiv.innerHTML = LoadFile(File)
End Sub
************************************************************
Function CheckProcesses()
dim startLine
On Error Resume Next
Dim fso,F,ReadMe,Tab,i,paragraphe
Set fso = CreateObject("Scripting.FileSystemObject")
Set F = fso.OpenTextFile(File,1)
LoadFile = Err.Number
If Err.Number <> 0 Then
MsgBox Err.Description,16," Error"
Exit Function
End If
ReadMe = F.ReadAll
Tab = split(ReadMe,vbcrlf)
For i = lbound(Tab) to ubound(Tab)
paragraphe=paragraphe & Tab(i) & "<br>"
Next
if ubound(Tab) > 2 Then
startLine = ubound(Tab) - 2
else
startLine = 0
end if
For i = startLine to ubound(Tab)
paragraphe=paragraphe & Tab(i) & "<br>"
Next
LoadFile = paragraphe
End Function
</script>
<input type="button" name="Log" id="Start" value="Log Dctm" onclick="CheckProcesses()"></html>
Thanks and regards
Deb
Another solution that avoids memory exhaustion with large files:
filename = "C:\path\to\your.txt"
numlines = 3
Set fso = CreateObject("Scripting.FileSystemObject")
'create and initialize ring buffer
ReDim buf(numlines-1)
For n = 0 To UBound(buf)
buf(n) = Null
Next
i = 0
'read lines into ring buffer
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
buf(i) = f.ReadLine
i = (i+1) Mod numlines
Loop
f.Close
'output ringbuffer content (skip null values)
For n = 1 To numlines
If Not IsNull(buf(i)) Then WScript.Echo buf(i)
i = (i+1) Mod numlines
Next
The array buf in combination with the index variable i and the modulo operation serves as a ring buffer containing the last lines read from the file (numlines at most).
At the end of the second loop (the one reading the input file), the index i points towards the array field after the one containing the last line read from the file, i.e. the beginning of the buffer.
The Null values from the array initialization let the output routine "slide" to the first content line (or the end of the buffer) if less than numlines lines were read from the file. The variable n in the output loop is just a counter so that the numlines elements from the ring buffer are read starting at index i and ending at index i-1 (modulo wrapping).
Given an array of lines (Tab), the last n lines to display start from UBound(Tab) - n + 1 and end with UBound(Tab). You should test for 'less than n lines in Tab' and for 'is last line of Tab empty (trailing EOL)'.
I am not able to test this, but If you know the UBound of the variable Tab, then the last three lines are UBound(tab)-2, UBound(tab)-1 and UBound(tab).
For i = ubound(Tab) - 2 to ubound(Tab)
paragraphe=paragraphe & Tab(i) & "<br>"
Next
Of course this requires that you have at least 3 lines in your log file, so, perhaps a little check should be done before entering the loop
dim startLine
if ubound(Tab) > 2 Then
startLine = ubound(Tab) - 2
else
startLine = 0
end if
For i = startLine to ubound(Tab)
paragraphe=paragraphe & Tab(i) & "<br>"
Next
Another solution
You can use this function :
Function ExtractLinesFromTextFile(ByRef TextFile, ByRef FromLine, ByRef ToLine)
Option Explicit
Dim Title,FromLine,ToLine,fso,Readfile,strBuff,InputFile,TotalNbLines
Title = "Extract Lines From TextFile © Hackoo 2014"
InputFile = "c:\test.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set Readfile = Fso.OpenTextFile(InputFile,1)
strBuff = Readfile.ReadAll
TotalNbLines = Readfile.Line
Readfile.Close
MsgBox "The total number of lines in this file """& InputFile &""" = "& TotalNbLines,VbInformation,Title
'To extract the 3 last lines
MsgBox ExtractLinesFromTextFile(InputFile,TotalNbLines - 2,TotalNbLines),64,Title
'*********************************************************************************************************
Public Function ExtractLinesFromTextFile(ByRef TextFile, ByRef FromLine, ByRef ToLine) '<-- Inclusive
Const TristateUseDefault = -2 'To Open the file using the system default.
On Error Resume Next
If FromLine <= ToLine Then
With CreateObject("Scripting.FileSystemObject").OpenTextFile(TextFile,1,true,TristateUseDefault)
If Err.number <> 0 Then
MsgBox err.description,16,err.description
Exit Function
Else
Do Until .Line = FromLine Or .AtEndOfStream
.SkipLine
Loop
Do Until .Line > ToLine Or .AtEndOfStream
ExtractLinesFromTextFile = ExtractLinesFromTextFile & (.ReadLine & vbNewLine)
Loop
End If
End With
Else
MsgBox "Error to Read Line in TextFile", vbCritical,"Error to Read Line in TextFile"
End If
End Function
'*********************************************************************************************************

List all access tables in Text file or excel

I have code that will list tables names, how can I export this to a text file?
For Each tbl In db.TableDefs
If Left$(tbl.Name, 4) <> "MSys" Then
Debug.Print tbl.Name & " " & tbl.DateCreated & " " & _
tbl.LastUpdated & " " & tbl.RecordCount
See the MSDN article on how to create a text file:
http://msdn.microsoft.com/en-us/library/aa265018(v=vs.60).aspx
Modified slightly for your needs, you will have to tweak it to define db and TableDefs etc:
Sub CreateAfile
Dim fs as Object, a as Object
Dim lineText as String
#Create and open text file for writing:
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("c:\testfile.txt", True)
'#Iterate over your TableDefs
For Each tbl In db.TableDefs
If Left$(tbl.Name, 4) <> "MSys" Then
lineText = tbl.Name & " " & tbl.DateCreated & " " & _
tbl.LastUpdated & " " & tbl.RecordCount
'# Adds a line to the text file
a.WriteLine(lineText)
End If
Next
'#Close the textfile
a.Close
End Sub
You can use simple File I/O to write to a textfile. MSDN: Write# Statement
Here is the example from that page:
Open "TESTFILE" For Output As #1 ' Open file for output.
Write #1, "Hello World", 234 ' Write comma-delimited data.
Write #1, ' Write blank line.
Dim MyBool, MyDate, MyNull, MyError
' Assign Boolean, Date, Null, and Error values.
MyBool = False: MyDate = #2/12/1969#: MyNull = Null
MyError = CVErr(32767)
' Boolean data is written as #TRUE# or #FALSE#. Date literals are
' written in universal date format, for example, #1994-07-13#
'represents July 13, 1994. Null data is written as #NULL#.
' Error data is written as #ERROR errorcode#.
Write #1, MyBool; " is a Boolean value"
Write #1, MyDate; " is a date"
Write #1, MyNull; " is a null value"
Write #1, MyError; " is an error value"
Close #1 ' Close file.
Change the file name, and extension, to, for example, "C:\SomeFolder\myfile.txt".
There are other, more sophisticated, ways to do this, including using the FileSystemObject as shown in the link David provided.
This will work as a straight copy/paste. Just change the output file name to whatever you want. It outputs the metadata you requested line by line toa .txt
Dim db As DAO.Database
Set db = CurrentDb
Dim filename As String
filename = "C:\Users\Scotch\Desktop\now\t.txt" 'add your file name here
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fs, f, ts, s
Set fs = CreateObject("Scripting.FileSystemObject")
fs.CreateTextFile filename 'Create a file
Set f = fs.GetFile(filename)
Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
For Each tbl In db.TableDefs
If Left$(tbl.name, 4) <> "MSys" Then
ts.Write tbl.name & " " & tbl.DateCreated & " " & _
tbl.LastUpdated & " " & tbl.RecordCount & vbNewLine
End If
Next
ts.Close