Read a Text File with Thousands Rows and Several Columns in VB6 - vb6

I try to read my text file with thousands rows and several columns in it, but VB6 limit me with only 338 rows for the entire program. Can anyone give me solution for that problem?
This is the code I already try (that dat is a text file):
Public TF As Integer, SF As String, NoRs As Integer
Public Type tFile
Number As String
Name As String
NIM As String
Class As String
Room As String
Department As String
Faculty As String
Univ As String
Role As String
End Type
Public myFile(1 To 2650) As tFile '2650 is Number of Rows in my Text File
Public Sub cFile()
TF = FreeFile
SF = App.Path & IIf(Right$(App.Path, 1) = "\", "", "\") & "String\myfile.dat"
Open SF For Input As #TF
NoRs = 0
Do Until EOF(TF)
NoRs = NoRs + 1
With myFile(NoRs)
Input #TF, _
.Number, _
.Name, _
.NIM, _
.Class, _
.Room, _
.Department, _
.Faculty, _
.Univ, _
.Role
End With
Loop
Close #TF
End Sub
It work until Row 338, but if I scroll down pass that row, it will out of range.

Related

Reading a specified line of an external file on Visual Basic [duplicate]

I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.
Here is my code:
Public Class Form1
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
Dim writer As New System.IO.StreamWriter("/text.txt", True)
writer.WriteLine(txtFirstName.Text)
writer.WriteLine(txtLastName.Text)
writer.WriteLine("-------------------------------------")
writer.Close()
End Sub
Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
Dim reader As New System.IO.StreamReader("/text.txt")
Dim FirstName, LastName As String
FirstName = reader.ReadLine()
LastName = reader.ReadLine()
reader.Close()
txtFirstName.Text = FirstName
txtLastName.Text = LastName
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtFirstName.Clear()
txtLastName.Clear()
End Sub
End Class
Any help would be appreciated. Thanks!
You will have to read all lines up to the one you're interested in. For example:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeded!
Return line
End Using
End Function
This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.
If you frequently need to load a specific line, you have some more options:
Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.
Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.
Try this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\text.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
txtFirstName.Text = ReadLine(5, allLines)
txtLastName.Text = ReadLine(6, allLines)
End Sub
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
If you had a file with this:
Line 1
Line 2
Line 3
Line 4
My Name
My LastName
your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.
This is very simple, try this:
Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3
myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString
Yet another option
Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
Dim nthLine As String = Nothing
Dim n As Integer
Try
Using sr As StreamReader = New StreamReader(fileAndPath)
n = 0
Do While (sr.Peek() >= 0) And (n < lineNumber)
sr.ReadLine()
n += 1
Loop
If sr.Peek() >= 0 Then
nthLine = sr.ReadLine()
End If
End Using
Catch ex As Exception
Throw
End Try
Return nthLine
End Function
i tried this and it works fine. using VB Express
content inside test.txt:
line1
line2
1
John
then in the form i add
textbox1
textbox2
label1
label2
and a button.
code inside the button:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim myLine As String
Dim lineNumber0 As Integer
lineNumber0 = 0
Dim lineNumber1 As Integer
lineNumber1 = 1
Dim lineNumber2 As Integer
lineNumber2 = 2
Dim lineNumber3 As Integer
lineNumber3 = 3
TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString
End Sub
Here's a simple but effective solution:
Dim Reader As String = System.IO.File.ReadAllLines("C:\File.txt")(1)
MsgBox("Line 1: " + Reader)
The MsgBox should show the first line of C:\File.txt.

error mismatch VBA

enter image description hereI'm getting hard time figuring what is going on in my code. It keeps saying "run-time error:'13' ". How can I handle this error?
Dim ws As Worksheet
Dim rearr(), wrarr()
Dim fName As String
Dim rowno As Long, colno As Long, rec As Long
Dim cnt As Long, cnt2 As Long
Dim delim As String
'specify output sheet
Set ws = Worksheets("1.Locations")
'specify text file to read (.csv in this example)
fName = "C:\Users\HP\Desktop\names.csv"
'set text file delimiter
delim = "," 'for Tab delimiter use delim = Chr(9)
ifnum = FreeFile
'set start row/col for text data to be placed ("A1" in this example)
rowno = 3 'row 1
colno = 2 'col A
With ws
Open fName For Input Access Read As #ifnum
rec = 0
Do While Not EOF(ifnum)
Line Input #ifnum, tmpvar
rec = rec + 1
'Put whole record into array
ReDim Preserve rearr(1 To rec)
rearr(rec) = tmpvar
'Split fields into a second array
wrarr = Split(rearr(rec), delim)
cnt2 = UBound(wrarr)
'Write fields out to specified ws range, one row per record
For cnt = 0 To cnt2
ws.Cells(rowno, colno + cnt) = wrarr(cnt)
Next cnt
rowno = rowno + 1
Loop
Close #ifnum
End With
I have reproduced your error.
In your declarations, change
Dim wrarr()
to
Dim wrarr

How to display length of word count in vb?

So I've been trying for hours to figure out how to display the length of word count in vb.
For example, if I type in a sentence in a rich textbox and I click a button, I want a form to show up listing the number of one-letter words, two-letter words, three-letter words and so on within that sentence. The number of words of specific length will be outputted in labels, of course.
I found this short code online for word count:
dim wordcount as integer
dim a as string() = RichText.Text.Split(" ")
wordcount = a.length
However, I'm not sure if this code can be used to get the length of word count. Any ideas of how I can achieve outputting the number of words of a specific length in a label? Thank you.
What about something like:
Private Sub mnuCount_Click()
Const DELIMITERS As String = vbNewLine & " !"",.:;?"
Dim WordCounts(1 To 100) As Long
Dim Msg As String
Dim I As Integer
Dim WordCount As Long
With RTB
.Visible = False
.SelStart = 0
Do
.UpTo DELIMITERS, vNegate:=True
.Span DELIMITERS, vNegate:=True
If .SelLength > 0 Then
WordCounts(.SelLength) = WordCounts(.SelLength) + 1
.SelStart = .SelStart + .SelLength
Else
Exit Do
End If
Loop
.SelStart = 0
.Visible = True
End With
Msg = "Length" & vbTab & "Count"
For I = 1 To 100
If WordCounts(I) > 0 Then
Msg = Msg & vbNewLine _
& CStr(I) & vbTab & CStr(WordCounts(I))
WordCount = WordCount + WordCounts(I)
End If
Next
Msg = Msg & vbNewLine _
& "Grand total:" & vbNewLine _
& vbTab & CStr(WordCount)
MsgBox Msg
End Sub
Pradnya's code, translated to VB6:
Option Explicit
Private Sub Command1_Click()
Dim str As String
Dim splitStr() As String
Dim i As Integer
str = "ABC DEF GHIJ KLMNOPQ"
splitStr = Split(str, " ")
MsgBox "Number of words = " & UBound(splitStr) + 1 & vbCrLf & _
"Average Length = " & Len(Replace(str, " ", "")) / (UBound(splitStr) + 1)
End Sub
I made a few simplifications as well. There's no need to go through the loop to get the average. All you have to do to get the length of the whole is remove the spaces and divide by the number of elements in the array.
However, if you want to get a count of the number of words of each length, you'll have to loop through the array, getting the length of each word and storing those values one by one. Best way to do that is to set a reference to scrrun.dll (Windows Scripting Runtime) and use a Dictionary object to store the values.

populating a matrix in vba

I'm trying to populate a matrix from three columns in a worksheet. My code is supposed to find a value in the first column, match it to the y-axis, then search the second column for a value, match it to a column header in the x-axis, and then paste the value from the third column in the cell activated by the row/column match. Does anyone see what's wrong with my code? I keep getting a "object variable or with block variable not set" error:
Sub Button1_Click()
Application.ScreenUpdating = False
Dim filePath As String
Dim strDate As String
Dim strMatchJE As String
Dim strMatchComponent As String
Dim wSheet As Worksheet
Dim wBook1 As Workbook
Set wSheet = ThisWorkbook.Sheets("Sheet1")
'Activate Journal Entry Number
strMatchJE = Columns("A").Find(what:="", after:=wSheet.Cells(1, 1), LookIn:=xlValues).Activate
aString = Left(originalString, 1)
strMatchJE = wSheet.Cells.Find(what:=aString, after:=Wbook.Cells(1, 1), _
LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=True).Address
'Activate component
strMatchComponent = Columns("B").Find(what:="", after:=wSheet.Cells(1, 1), LookIn:=xlValues).Activate
bString = Left(originalString, 1)
strMatchJE = wSheet.Cells.Find(what:=aString, after:=Wbook.Cells(2, 1), _
LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, MatchCase:=True).Address
strEnterAmount = Columns("T").Find(what:="", after:=wSheet.Cells(3, 1), LookIn:=xlValues).Activate
firstrow = ActiveCell.Row
firstcolumn2 = ActiveCell.Column
firstrow = firstrow + 1
Rows(firstrow).Columns(firstcolumn2).Select
strEnterAmount.Paste
End Sub

List the IP Address of all computers connected to LAN in vb6

I want to list all the IP Address connected LAN into a listbox in VB6. Ive visited this. But I want to do this in VB6. I've no idea about how to do this. Any help is appreciated.
Using a WinSock control (wsck) purely for being a way to get the local IP address, use this code:
Option Explicit
Private Type IPAddr
s_b1 As Byte
s_b2 As Byte
s_b3 As Byte
s_b4 As Byte
End Type
Private Type IPAddrCompat
ul As Long
End Type
Private Type MacAddress
s_b1 As Byte
s_b2 As Byte
s_b3 As Byte
s_b4 As Byte
s_b5 As Byte
s_b6 As Byte
unused As Integer
End Type
Private Declare Function SendARP Lib "Iphlpapi.dll" ( _
ByVal DestIP As Long, _
ByVal SrcIP As Long, _
ByRef pMacAddr As MacAddress, _
ByRef PhyAddrLen As Long _
) As Long
Private Sub cmdGetIPs_Click()
Dim nIndex As Long
Dim vasLocalIP As Variant
Dim uIPAddr As IPAddr
Dim uIPAddrCompat As IPAddrCompat
Dim uMacAddr As MacAddress
Dim nMacAddrLen As Long
vasLocalIP = Split(wsck.LocalIP, ".")
uIPAddr.s_b1 = CByte(vasLocalIP(0))
uIPAddr.s_b2 = CByte(vasLocalIP(1))
uIPAddr.s_b3 = CByte(vasLocalIP(2))
' Iterate through all valid addresses in the final quartet.
For nIndex = 1 To 254
uIPAddr.s_b4 = CByte(nIndex)
LSet uIPAddrCompat = uIPAddr ' Convert 4 bytes into 1 long.
nMacAddrLen = 8 ' Indicate that we are allocating a buffer with 8 bytes.
' Try to find the MAC address for this IP.
If SendARP(uIPAddrCompat.ul, 0&, uMacAddr, nMacAddrLen) = 0 Then
' MAC addresses are 6 bytes long.
If nMacAddrLen = 6 Then
vasLocalIP(3) = CStr(nIndex)
Debug.Print Join(vasLocalIP, "."), MacAddrString(uMacAddr, nMacAddrLen)
End If
End If
Next nIndex
End Sub
' Returns the MAC address as a six byte hex string.
Private Function MacAddrString(ByRef the_uMacAddr As MacAddress, ByVal the_nMacAddrLen) As String
With the_uMacAddr
MacAddrString = Hex2(.s_b1) & ":" & Hex2(.s_b2) & ":" & Hex2(.s_b3) & ":" & Hex2(.s_b4) & ":" & Hex2(.s_b5) & ":" & Hex2(.s_b6)
End With
End Function
' Returns the byte as a two digit hex string.
Private Function Hex2(ByVal the_byt As Byte) As String
Hex2 = Hex$(the_byt)
If Len(Hex2) = 1 Then
Hex2 = "0" & Hex2
End If
End Function

Resources