HTA to read a text file and populate drop down box - text

A text file example will include the following data, a name and associated IP address, in this format:
name;IP
i.e.
harry;192.168.1.14
billy;192.168.1.22
Using VBS to read the text file and split the data into 2 parts:
Sub LoadDropDownName
Set obj = CreateObject("Scripting.FileSystemObject") 'Creating a File Object
Const ForReading = 1 'Defining Constant Value to read from a file
Set obj1 = obj.OpenTextFile("savedhosts.txt", ForReading) 'Opening a text file and reading text from it
Dim str, str1
str = obj1.ReadAll 'All text from the file is read using ReadAll
MsgBox str 'Contents of a file will be displayed through message box
'Do While obj1.AtEndofStream 'Reading text line wise using Do Loop and ReadLine
' str1 = obj1.ReadLine
' MsgBox str1
'Loop
Do Until obj1.AtEndOfStream
strNextLine = obj1.ReadLine
arrServiceList = Split(strNextLine, ";")
Set objOption = document.CreateElement("OPTION")
objOption.title = arrServiceList(0)
objOption.value = arrServiceList(1)
LoadDropDownName.Add(objOption)
MsgBox "arrServiceList(0) = " & arrServiceList(0)
MsgBox "arrServiceList(1) = " & arrServiceList(1)
Loop
'MsgBox ""
obj1.Close 'Closing a File
Set obj = Nothing 'Releasing File object
End Sub
MsgBox str works as it displays all the data from the "savedhosts.txt" file as expected.
However I cant get
MsgBox "arrServiceList(0) = " & arrServiceList(0)
MsgBox "arrServiceList(1) = " & arrServiceList(1)
to display in a box. I have moved the MsgBox command to below the Loop line.
Loop
MsgBox "arrServiceList(0) = " & arrServiceList(0)
MsgBox "arrServiceList(1) = " & arrServiceList(1)
'MsgBox ""
obj1.Close 'Closing a File
Set obj = Nothing 'Releasing File object
I received an error:
Type mismatch 'arrServiceList'
The HTML part that should capture the data from the Sub:
<input type='text' maxlength="15" class="enterhostip" id="INPUT-IP" name='text1'/>
INPUT IP: user can input a new IP and will auto change when 'Saved Hostname' has chosen a new value.
<input type="text" maxlength="20" name="hostname" id="hostname" />
Hostname: user can input a new name for the host
<select id="savedhostname" maxlength="20" name="savedhostname" onchange="vbscript:LoadDropDownName" class="pwhost" />
Saved Hostname: dropdown data showing only the name in the savedhosts.txt file. Changing the name will execute the
LoadDropDownName script and change the value of "IP-Input".
If someone can show me an example of similar code (using VBScript) to read the contents of this text file and show the names only in a html drop down box while using a html single line text input area to auto fill the associated IP address?
I have searched for an example of this method but cannot find any that meet this simple criteria!

I think the issue might be that you read the whole file (I suspect for debugging purposes) which ends the stream, and then obj.AtEndOfStream becomes true. Therefore your loop doesn't execute.
str=obj1.ReadAll ' ends the stream
You could close then reopen the stream
Set obj1 = obj.OpenTextFile("savedhosts.txt", ForReading) 'Opening a text file and reading text from it
Dim str,str1
str=obj1.ReadAll 'All text from the file is read using ReadAll
Msgbox str
obj1.Close
Set obj1 = obj.OpenTextFile("savedhosts.txt", ForReading) ' etc
or just omit the obj1.ReadAll bit, or process str as one big chunk of text

Related

Read a text file for a specific string and open msgbox if not found

How do I open a text file and look for a specific string?
I want that the string "productactivated=true" determines whether to display a message on the Userform telling the user to activate.
A few days ago I asked for help with opening a text file and doing some reading and writing, so I came up with this
Open "application.txt" For Output As #1
ClngLine = lngLine + 1
Line Input #f, strLine
If InStr(1, strLine, strSearch, vbBinaryCompare) > 0 Then
MsgBox "Search string found in line " & lngLine, vbInformation
blnFound = True
Close #1
For your solution two files will be used showing how to read and write to text files. The writing was added just to show you how to do it but does not seem to be needed for your solution per your question statement. For this solution purpose, all the files are in the same folder.
The first file is the file being read from. For the demo purpose, since not data was supplied it was created with the following data and named "TextFile.txt":
This is the first line.
This is the second line and has productactivated=true.
Third line lays here.
productactivated=true is found in line four.
The second file is the file being written to. For the demo purpose just to show how it is done, but per your question isn't needed, and named "TextFile.txt":
This is the first line.
This is the second line and has productactivated=true.
Third line lays here.
productactivated=true is found in line four.
The VBA code:
Sub search_file()
Const ForReading = 1, ForWriting = 2
Dim FSO, FileIn, FileOut, strSearch, strTmp
'FileSystemObject also called as FSO, provides an easy object based model to access computer’s file system.
Set FSO = CreateObject("Scripting.FileSystemObject")
'Set FileIn to the file for reading the text into the program.
Set FileIn = FSO.OpenTextFile("TextFile.txt", ForReading)
'Set FileOut to the file for writing the text out from the program.
'This was added just to show "how to" write to a file.
Set FileOut = FSO.OpenTextFile("TextFileRecordsFound.txt", ForWriting, True)
'Set the variable to the string of text you are looking for in the file you are reading into the program.
strSearch = "productactivated=true"
'Do this code until you reach the end of the file.
Do Until FileIn.AtEndOfStream
'Store the current line of text to search to work with into the variable.
strTmp = FileIn.ReadLine
'Determines whether to display a message
'(Find out if the search text is in the line of text read in from the file.)
If InStr(1, strTmp, strSearch, vbTextCompare) > 0 Then
'Display a message telling the user to activate.
MsgBox strSearch & " was found in the line:" & vbNewLine & vbNewLine & strTmp, , "Activate"
'Write the line of text to an external file, just to demo how to.
FileOut.WriteLine strTmp
End If
Loop 'Repeat code inside Do Loop.
'Close files.
FileIn.Close
FileOut.Close
End Sub

Ignoring blank lines and spaces in text files when reading

I have a text file with file addresses listed line by line.
Sometimes, however, the users go in there and accidentally add a space or a blank line between the addresses and that crashes the entire code.
How could I avoid this when reading the file using VBA?
This is the current block used to open the text file and read addresses line by line:
Set ActiveBook = Application.ActiveWorkbook
PathFile = ActiveWorkbook.Path & "\FilePaths.txt"
Open PathFile For Input As #1
Do Until EOF(1)
Line Input #1, SourceFile
Set Source = Workbooks.Open(SourceFile)
You will add two lines which will ignore blank lines and spaces like this:
Line Input #1, SourceFile
SourceFile = Trim(SourceFile) '~~> This will trim all the spaces
If Not SourceFile = "" Then '~~> This will check if lines is empty
Set Source = Workbooks.Open(SourceFile)
Suggest you add further code to
test if the file actually exists
test if the file is of a valid type for excel to open
code
Dim SourceFile As String
Dim PathFile As String
Set ActiveBook = Application.ActiveWorkbook
PathFile = ActiveWorkbook.Path & "\FilePaths.txt"
Open PathFile For Input As #1
Do Until EOF(1)
Line Input #1, SourceFile
SourceFile = Trim$(SourceFile)
If Len(Dir(ActiveWorkbook.Path & "\" & SourceFile)) > 0 Then
Select Case Right$(SourceFile, Len(SourceFile) - InStrRev(SourceFile, "."))
Case "xls", "xls*"
Set Source = Workbooks.Open(ActiveWorkbook.Path & "\" & SourceFile)
Case Else
Debug.Print "source not valid"
End Select
End If
Loop
Thanks for the code.
I did some small changes so I can reuse it in many different cases and call at any point of the code, using up to 3 different args (you may increase if you wish). like this below example.
note: you may change "totalBananas,EN2003" to anything you find impossible to exist in your files... I used it this way because I am not sure how to declare the args as optional :-p I don't think they are really possible to be optional anyway.
...
Call FixTextFile(file_name, "blabla", "0000", "")
...
Sub FixTextFile(inFile As Variant, fixArg1 As String, fixArg2 As String, fixArg3 As String)
Dim resArg1, resArg2, resArg3 As Long
Dim outFile As String
Dim data As String
If fixArg1 = "" Then fixArg1 = "totalBananas,EN2003"
If fixArg2 = "" Then fixArg2 = "totalBananas,EN2003"
If fixArg3 = "" Then fixArg3 = "totalBananas,EN2003"
Open inFile For Input As #1
outFile = inFile & ".alt"
Open outFile For Output As #2
Do Until EOF(1)
Line Input #1, data
resArg1 = InStr(1, data, fixArg1)
resArg2 = InStr(1, data, fixArg2)
resArg3 = InStr(1, data, fixArg3)
If Trim(data) <> "" And resArg1 < 1 And resArg2 < 1 And resArg3 < 1 Then
Print #2, data
End If
Loop
Close #1
Close #2
Kill inFile
Name outFile As inFile
MsgBox "File alteration completed!"
End Sub

Transfering Data from Multiple HTML Files into Excel

Suppose I have a number of HTML documents, each of which has the same format. While the information in these documents is not in tables there are always specific key words that give away where the desired information is located. Is there a way to set up a macro so that Excel searches each of these documents for a specific 'title', returns all characters after the first white space of the title, and stops only once it reaches two white spaces in a row? The idea would be to then place all of this information into one column and begin the process again with another 'title'. I am really not sure where to start with such a macro.
this should get you close
MyPath = "path to folder containing HTML files"
Set fso = CreateObject("Scripting.FileSystemObject")
Set my_files = fso.getfolder(MyPath).Files
For Each f1 In my_files
Set TxtStream = fso.OpenTextFile(path_fname, ForReading, False, TristateUseDefault)
my_var = ""
Do While Not TxtStream.AtEndOfStream
my_var = my_var & TxtStream.ReadLine
Loop
TxtStream.Close
pos_1 = instr(1, my_var, "your Title")
pos_2 = instr(pos_1, my_var, " ")
my_txt = mid(my_var, pos_1, pos_2 - pos_1)
' do whatever with the captured text
Next

insert part of file name into (first) column of csv

I have hundreds of csv files with filenames in the following format: yyyymmdd_something.csv, e.g. 20131213_something.csv ... i.e., an underscore separates the date from the rest of the filename.
Each of has the following fields:
Make, Model, metric 1, metric 2, etc.
I would like to:
1) Insert the date from the file name into (preferably first) column, like so:
Date, Make, Model, metric 1, metric 2, etc.
But really it can be any column because once in Excel, it is a simple matter to re-arrange it. The date should be added as mm/dd/yyyy as it is what Excel understands.
2) After inserting the date, I would like to merge all the csv into 1 big csv file.
I'm using a Win7 machine so a dos batch file would probably be the simplest way to run it for me but if I had to, I can install perl or something to do this. Any help would be deeply appreciated. There was a thread that talks about inserting the whole file name but I really need only the date part added.
Hi this can be done by vbscript, the code is below:
Create a VBS file (notepad can do it, just paste following code and save file as .vbs)
You can drop 20-50 files (yyyymmdd_something.csv) as the same time to the icon of this vbs file and it will process as you wish :)
Please create Summary.csv file first and update its full path to pSumaryCSV = "......\Summary.csv"
'USAGE:
'CREATE A VBSCRIPT FILE .VBS WITH THIS CONTENT
'CREATE SUMMARY CSV FILE AND UPDATE ITS FULL PATH IN pSumaryCSV
'DRAG AND DROP YOUR ORIGINAL CSV FILE TO THIS VBS FILE ICON, IT CAN PROCESS MULTIPLE FILE (BUT DON'T PUT TOO MANY AS ONE)
'THIS CODE WILL CREATE A NEW CSV FILE <ORIGINAL FILE NAME>_DATE_ADDED.csv
'AND UPDATE Summary.csv file.
Set objArgs = WScript.Arguments
Set objFso = createobject("scripting.filesystemobject")
dim objOrgFile
dim arrStr ' an array to hold the text content
dim sLine ' holding text to write to new file
'Location of the summary file - Full path. If it is not exist then create it first.
'The summary one should have all column lable since following code will not add label to it.
pSumaryCSV = "......\Summary.csv"
'Open the summary file to append data
set aSummaryFile = objFso.OpenTextFile(pSumaryCSV, 8) '2=Open for writing 8 for appending
'Looping through all dropped file
For t = 0 to objArgs.Count - 1
' Input Path
inPath = objFso.GetFile(wscript.arguments.item(t))
inName = objFso.GetFileName(inPath)
' OutPut Path
outPath = replace(inPath, objFso.GetFileName(inPath), left(inName, InStrRev(objFso.GetFileName(inPath),".") - 1) & "_DATE_ADDED.csv")
' The original file
set objOrgFile = objFso.OpenTextFile(inPath)
'Now Creating the file can overwrite exiting file with same name
set aNewFile = objFso.CreateTextFile(outPath, True)
aNewFile.Close
'Open the new file (...._DATE_ADDED.csv) to appending data
set aNewFile = objFso.OpenTextFile(outPath, 8) '2=Open for writing 8 for appending
'=======================================================================
'Process first line, this firstline will not be added to SummaryCSV File
If Not objOrgFile.AtEndOfStream Then
arrStr = split(objOrgFile.ReadLine,",")
sLine = "Date," 'This will add Date label for
For i=lbound(arrStr) to ubound(arrStr)
sLine = sLine + arrStr(i) + ","
Next
'Writing first line to new file but not the summary one.
aNewFile.WriteLine left(sLine, len(sLine)-1) 'Get rid of that extra comma from the loop
end if
'=======================================================================
' Reading subsequent line and writing it to new file
Do Until objOrgFile.AtEndOfStream
arrStr = split(objOrgFile.ReadLine,",")
'Get the mm/dd/yyyy path from file name yyyymmdd
sLine = ""
sLine = sLine + Mid(inName,5,2) + "/" 'Get mm from file name
sLine = sLine + Mid(inName,7,2) + "/" 'Get dd from file name
sLine = sLine + Mid(inName,1,4) + "/" 'Get yyyy from file name
sLine = Sline + "," 'This will add a column
For i=lbound(arrStr) to ubound(arrStr)
sLine = sLine + arrStr(i) + ","
Next
'Writing data to new file
aNewFile.WriteLine left(sLine, len(sLine)-1) 'Get rid of that extra comma from the loop
'Writing data to summary file
aSummaryFile.WriteLine left(sLine, len(sLine)-1)
Loop
'Closing new file
aNewFile.Close
Next ' This is for next file
'Close Summary File
aSummaryFile.Close
set aSummaryFile=nothing
set aNewFile=nothing
set objFso = nothing
set objArgs = nothing

Simple VBA/Macro need to create a new text file with the contents of active sheet without changing filename

I need to export data in a sheet to a text file without changing the file name (i.e. not doing "save as". Also it would be great if the file name could look at the previous like file name in the folder and increase by 1 digit (i.e. :file_1.txt, file_2.txt, etc.)...
Thanks!!
If you want to avoid the current name of your excel file being changed, just save the current worksheet, not the whole workbook (the VBA equivalent of the SaveAs function is ActiveWorkbook.SaveAS, to save just the current sheet use ActiveSheet.SaveAS).
You can use the following macro:
Sub Macro1()
Application.DisplayAlerts = False
ActiveSheet.SaveAs Filename:="NewFile.txt", FileFormat:=xlTextWindows
Application.DisplayAlerts = True
End Sub
Toggling the DisplayAlerts property avoids a message box that is displayed if the given file already exists.
If want to save more than one sheet, you need to iterate through the Sheets collection of the ActiveWorkbook object and save each sheet to a separate file.
You can get a new file name as illustrated below, it includes a date. If you would like to add some details on what you want to export, you may get a fuller answer.
Function NewFileName(ExportPath)
Dim fs As Object '' or As FileSytemObject if a reference to
'' Windows Script Host is added, in which case
'' the late binding can be removed.
Dim a As Boolean
Dim i As Integer
Dim NewFileTemp As string
Set fs = CreateObject("Scripting.FileSystemObject")
NewFileTemp = "CSV" & Format(Date(),"yyyymmdd") & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = 1
Do While a
NewFileTemp = "CSV" & Format(Date(),"yyyymmdd") & "_" & i & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = i + 1
If i > 9 Then
'' Nine seems enough times per day to be
'' exporting a table
NewFileTemp = ""
MsgBox "Too many attempts"
Exit Do
End If
Loop
NewFileName = NewFileTemp
End Function

Resources