Error: Object Required: 'example' - vba

Hey I have this do until loop that takes a text file made into a string ("strnotapprovedData") and then calls this function that runs a command to delete the share. I keep getting the error object required: "xxxx". How do I fix this is the problem the function the loop statement or the string.
Function:
Function DeleteThisShare(Value)
DeleteThisShare = "net share " & Share & " \DELETE"
Set objShell = CreateObject("Wscript.Shell")
Msgbox AddQuotes(DeleteThisShare)
objShell.Run DeleteThisShare
End Function
Loop Statement:
Do Until strnotapprovedData.AtEndOfStream
Dim objShare : objShare = Split(strnotapprovedData,vbCrLf)
notapprovedShares = objShare
DeleteThisShare(notapprovedShares)
Loop
String:
Dim notapprovedList, notapprovedShares
Set notapprovedList = objFSo.OpenTextFile ("C:\Users\abro\Shares_Not_Approved.txt")
Dim strnotapprovedFile, strnotapprovedData
strnotapprovedFile = ("C:\Users\abro\Shares_Not_Approved.txt")
strnotapprovedData = objFSO.OpenTextFile(strnotapprovedFile,ForReading).ReadAll
Reply to Chris Nielsen
Well I added this and the same problem still occurs
strnotapprovedData = objFSO.OpenTextFile(strnotapprovedFile,ForReading).ReadAll
Do Until objnotapprovedLines.AtEndOfStream
objnotapprovedLines = Split(Trim(strnotapprovedData),vbCrLf)
DeleteThisShare(objnotapprovedLines)
Loop

strnotapprovedData is set to a string as a result of the ReadAll method of the file system object. Since it is a string and not a stream, it will not have an AtEndOfStream property. Instead, you should split it on line breaks and loop over the resulting array.
Response to edit:
Your code does not show where objnotapprovedLines is being defined or initialized. From your usage, I presume it starts life as a stream, but I have no way to know that. However, on the first line after your DO, you overwrite it to be an array. Arrays do not have an AtEndOfStream property, so that would certainly cause the error, even if nothing else has.
Here is some untested code to try:
' Define a new variable called "notApprovedLines"
' VBScript is loosely-typed, so this could be anything at this point.
Dim notApprovedLines
' Read the contents of the file into the "notApprovedLines" variable.
' This assumes that you have a variable named "strnotapprovedFile" that
' contains the path to the file, as your example code indicates. At the
' end of this, the "notApprovedLines" variable contains the entire contents
' of the file as one giant string.
notApprovedLines = objFSO.OpenTextFile(strnotapprovedFile, ForReading).ReadAll
' Split the contents of the file into an array, so we can deal with one line at
' a time. After this, "notApprovedLines" will be an array of strings, with each
' entry representing one line of the original file.
notApprovedLines = Split(notApprovedLines, vbCrLf)
' Loop over those lines
Dim x, k, line
' This sets the upper boundary of the loop.
k = uBound(notApprovedLines)
' In VBScript, arrays start at zero. The "x" is our counter variable. Its
' value will be incremented with each iteration of the loop, so we hit the
' entries one at a time.
For x = 0 To k
' Trim whitespace away from each line. After this executes, the "line"
' variable will contain a single line from the file, as a string, without
' and leading or trailing whitespace.
line = Trim(notApprovedLines(x))
' We don't want to process blank lines, if any exist. This test lets us
' skip those. Any line that contained only whitespace would also be
' skipped here, since it's length would be zero after trimming away the
' whitespace.
If Len(line) > 0 Then
' This executes your function. I have not really proofed it very
' closely. Let's hope it works! =)
DeleteThisShare(line)
End If
Next

Related

Trying to close textfile after line is read

Im trying to output the data from the second line of my textfile to a datagridview but when doing so it is also outputting every line after the the second line. This is what I have tried. Thanks
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
For index = 1 To lines.Length - 1
Dim cells = lines(index).Split(","c)
dgvOutput.Rows.Add(cells)
FileClose()
It's outputting every line after the second line, because that's what you're telling it to do when you iterate through the array of strings returns from ReadAllLines.
IO.File.ReadAllLines does not leave an output stream open. The file is closed. What it does do, is return a zero-based (by default) array of the contents of the file, with line breaks being the delimiter for the split.
To just get the contents of the second line, using ReadAllLines, this is what you need:
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
If lines.length >= 2 Then
Dim cells = lines(1).Split(","c)
dgvOutput.Rows.Add(cells)
End If
Now, that does have the overhead of reading the entire file in. If you open the file using a reader object, then you only need to read the first and second lines of the file to get that second line.
That would be something like this:
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(OrderId & ".txt")
Dim a as String
' This reads the first line, which we throw away
reader.ReadLine()
a = reader.ReadLine()
reader.Close()
Dim cells = a.Split(","c)
dgvOutput.Rows.Add(cells)
You would need to test your explicit circumstances to determine which is better for what you're trying to do.
Your loop is executed over all lines skipping just the first line.
While I cannot see what happen in the FileClose call it seems to not have any sense because ReadAllLines has already closed the file.
You can get the second line of your file with a single line of code
Dim line as String = File.ReadLines(OrderID & ".txt").Skip(1).Take(1).FirstOrDefault()
' this check is required to avoid problems with files containing 0 or 1 line
if line IsNot Nothing Then
Dim cells = line.Split(","c)
dgvOutput.Rows.Add(cells)
End If
Notice that I have replaced the ReadAllLines with ReadLines. This is better because using this method you don't read all lines when you need only the second one (if it exists). More info at ReadLines vs ReadAllLines
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
Dim SecondLine = lines(1)
File.ReadAllLines opens and closes the file for you so there is not need to add code to close it.

Reading a particular line of a text file in an array in VB.NET

I am trying to read specific lines from a text file in an array (e.g. line 16,25,34, and so on). Could you please let me know if it is possible and how that could be done?
Thanks in advance,
Pouya
Yes it is possible. Since this is not a code based will elaborate how to achieve that. This will depends on the size of your target file. If the size in not to large for your PC's memory then you can read the whole textfile while reading keep the count.
Then start when the file has been read to end to go through your lines using regex.
Check:
VB.NET Read Certain text in a text file
your solution is here:
http://www.dreamincode.net/forums/topic/56497-go-to-a-particular-line-in-a-text-file-using-vbnet/
How to read a specific line from a text file in VB
Ok, here's I've also quoted the code to help you from the second last like I provided above. I'm sure you know how to get data from an Array so instead of line you will add your array.
Public Function
ReadSpecifiedLine(ByVal line As
Integer) As String
'create a variable to
hold the contents of the file
Dim contents As String = String.Empty
'create a variable to
hold our line contents
Dim lineText As String =
String.Empty
' always use a
try...catch to deal
' with any exceptions
that may occur
Try
'Using lineByLine As New IO.StreamReader(_fileName)
Dim lineCount As Integer = 0
While Not lineByLine.EndOfStream
lineByLine.ReadLine ()
If lineCount = line Then
' you can replace the line variable above or use the And Or to match the lines from your array.
lineText = lineByLine.ReadLine()
End If
lineCount += 1
End While
End Using
Catch ex As FileNotFoundException
lineText = String.Empty
_returnMessage = ex.Message
Catch ex As Exception
' deal with any errors
_returnMessage = ex.Message
End Try
Return lineText
End Function
Hope this helps you.(Sorry having some problems in code formatting it some part maybe not formeted, or visible. If End Function is not visible please refer to the link. I've tried so many times to formet this but it not properly formeted, I'm using a Mobile phone.)

Reset index of File object for reading several time

Now, I am writing a VBA program. In my program, firstly I need to count all line from a file. I need line count because of creating array for line in file. So, I used this code. It is OK.
'Open file
Set file = fsObject.OpenTextFile(filePath, ForReading)
'Read all line
file.ReadAll
'Get line count
lineCount = file.line
'Close file
file.Close
After getting line count, I want to subtract 2 from it for header and footer(the blank line). I don't know which word will be header. I only know row that they are first row and last row(the blank row).
'Remove header and blank line from line count
lineCount = lineCount - 2
And then, I wanna read that file line by line which are only useful for me and store all line in array. The problem is at that, when reading line by line, It is need to re-open file. Only after re-open, I can read line by line.
Because, "ReadAll" method is readed all line and the index of file object is shown "AtEndOfFile". So, I must re-open it. Please check my code.
'If line count is greater than 0, read again file to get data
If lineCount > 0 Then
'Re-define array size
ReDim lineList(lineCount) As String
'Here I opend it, I don't wanna open. I just want to set index of file object.
'Re-open file
Set file = fsObject.OpenTextFile(filePath, ForReading)
'Read file until end
Do Until file.AtEndOfStream
'If current line is not first line(header) or last line(blank line)
If line <> 0 And line <= lineCount Then
'Store line into array
lineList(index) = file.ReadLine
'Increase array index
index = index + 1
Else
file.ReadLine
End If
'Increase line index
line = line + 1
Loop
End If
But, I want another way. I don't wanna re-open file. I want to reset the index to the first line of file object. So, I don't need to re-open it.
I already search about it in internet. But, I didn't found any suggestions for that. Please help me. Thanks.
My approach is slightly different than your current approach, I would use the Binary read to read the file and save it in a temporary string, then use Split function to put them in an Array.
This method has one drawback as in the if the length (number of characters) of the file is greater than the size of a String variable then we might have issues but other than that. This is quite different approach.
Public Sub ReadFileData(filePath As String, Optional separatorStr As String = ";#;")
'******************************************************************************
' Opens a large TXT File, reads the data until EOF on the Source,
' then stores them in an Array
' Arguments:
' ``````````
' 1. The Source File Path - "C:\Users\SO\FileName.Txt" (or) D:\Data.txt
' 2. (Optional) Separator - The separator, you wish to use. Defauls to ';#;'
'*******************************************************************************
Dim strIn As String, tmpStr As String, lineCtr As Long
Dim tmpArr() As String
Open filePath For Input As #1
Do While Not EOF(1)
'Read one line at a time.
Line Input #1, strIn
tmpStr = tmpStr & Trim(strIn) & separatorStr
lineCtr = lineCtr + 1
Loop
Close #1
tmpArr = Split(tmpStr, separatorStr)
Debug.Print "Number of Elements in the Arrays is - " & UBound(tmpArr)
Debug.Print "Number of Lines Read is - " & lineCtr
End Sub

dispose of IO.File.ReadAllLines

I am reading very large text files (6-10 MB). I am splitting the text files in to multiple new text files. There is common "header" and "footer" in the "read" text file that I will store as variable to be called at later time. I can't figure out how to properly dispose of IO.File.ReadAllLines. I'm concerned this will be held in memory if I don't dispose of it properly.
Text.Dispose or Text.Close isn't valid.
Dim testHeader As String
Dim testSite As String
Dim testStart As String
Dim testStop As String
Dim testTime As String
Dim text() As String = IO.File.ReadAllLines("C:\Users\anobis\Desktop\temp.txt")
testHeader = text(0)
testSite = text(text.Length - 4)
testStart = text(text.Length - 3)
testStop = text(text.Length - 2)
testTime = text(text.Length - 1)
text.dispose()
Later in the program I will be initiating another StreamReader and want to avoid conflicts and memory resource issues. I am new at coding so be gentle! Thanks!
' Open temp.txt with "Using" statement.
Using r As StreamReader = New StreamReader("C:\Users\anobis\Desktop\temp.txt")
' Store contents in this String.
Dim line As String
line = r.ReadLine
' Loop over each line in file, While list is Not Nothing.
Do While (Not line Is Nothing)
If line Like (sourceSN.Text + "*") Then 'Substitute in source serial number "xxxxxx*"
file.WriteLine(line)
End If
' Read in the next line of text file.
line = r.ReadLine
Loop
End Using
file.WriteLine(testSite)
file.WriteLine(testStart)
file.WriteLine(testStop)
file.WriteLine(testTime)
' Close transfer.txt file
file.Close()
You don't need to dispose of it. It returns a managed string array, who's lifetime is managed by the garbage collector. Internally, File.ReadAllLines is disposing of the underlying native file handle it created to read all of the lines for you.

VBS Invalid Character

This is a simple VBS script. But when I double-click on this, I get Invalid Character 800A0408 on Line 1, Character 1, which I think is the first "Dim". I am new to VBS--can u tell me what I did wrong? FYI, I have an XP OS and IIS6 Manager installed.
' This script adds the necessary Windows Presentation Foundation MIME types
' to an IIS Server.
' To use this script, just double-click or execute it from a command line.
' Running this script multiple times results in multiple entries in the IIS MimeMap.
Dim MimeMapObj
Dim MimeMapArray
Dim WshShell
Dim oExec
Const ADS_PROPERTY_UPDATE = 2
' Set the MIME types to be added
Dim MimeTypesToAddArray = Array(".manifest", "application/manifest", ".xaml", _
"application/xaml+xml", ".application", "application/x-ms-application", _
".deploy", "application/octet-stream", ".xbap", "application/x-ms-xbap", _
".xps", "application/vnd.ms-xpsdocument")
' Get the mimemap object
Set MimeMapObj = GetObject("IIS://LocalHost/MimeMap")
' Call AddMimeType for every pair of extension/MIME type
For counter = 0 to UBound(MimeTypesToAddArray) Step 2
AddMimeType MimeTypesToAddArray(counter), MimeTypesToAddArray(counter+1)
Next
' Create a Shell object
Set WshShell = CreateObject("WScript.Shell")
' Stop and Start the IIS Service
Set oExec = WshShell.Exec("net stop w3svc")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
Set oExec = WshShell.Exec("net start w3svc")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
Set oExec = Nothing
' Report status to user
WScript.Echo "Windows Presentation Foundation MIME types have been registered."
' AddMimeType Sub
Sub AddMimeType(ByVal Ext, ByVal MType)
' Get the mappings from the MimeMap property.
MimeMapArray = MimeMapObj.GetEx("MimeMap")
' Add a new mapping.
i = UBound(MimeMapArray) + 1
ReDim Preserve MimeMapArray(i)
MimeMapArray(i) = CreateObject("MimeMap")
MimeMapArray(i).Extension = Ext
MimeMapArray(i).MimeType = MType
MimeMapObj.PutEx(ADS_PROPERTY_UPDATE, "MimeMap", MimeMapArray)
MimeMapObj.SetInfo()
End Sub
If you open the file with vim and use the ex command 'set list' it will show you any invisible characters that may be causing this issue.
Quoting http://classicasp.aspfaq.com/general/why-do-i-get-800a0408-errors.html
If you cut and paste code from other
sources (e.g. web sites, other
editors, etc) you often bring along
characters that don't show up in
Notepad but are, nonetheless, present
-- or do appear as non-prinatable characters, that look like little
squares. If you're looking at the line
in question and it isn't simply an
unclosed string or a premature
carriage return, try deleting the
line(s) altogether and re-typing them
by hand. This should eliminate the
possibility of 'invisible' problem
characters mucking up the stream.
Check the encoding when you save the file, must be ANSI in NotePad