Creating Access table from text file - database

I was wondering is it possible to create an Access Database table from a text file.
For example a text file like this:
#Tom
Age:12
Info: Tall
#Alice
Age: 20
Info: Nice
Should be converted to a table with 3 parameters (Name, Age and Info) containing the info of Tom and Alice.
A different example would be the text file:
Tim
-------
A tall 12 years old.
Good In basketball
Jak
-------
A short 30 years old guy.
Bad at sports
Bald
Which should be converted into a table containing 2 parameters-age and info.
If coding is required I'd prefer using c# though Java is also an option.
Thanks in advance :D

After a searching far and wide I found a solution.
I loaded the text into a string in c#, than built an excel table using Microsofts API.
After you've got an excel spreadsheet converting it to access is rather simple using Access' built-in functionaily

It likely easer to do this in VBA – and you not need to write some messy c# (however, if you are actually familer with c#, then any compentent coder can EASY read some VBA and just type in c# line for line – assuming you are actually familer with C#.
So the VBA to import the first text file and write out the data to a table will look like this:
Sub Import1()
Dim intfileH As Integer
Dim strBuf As String
Dim rst As DAO.Recordset
Dim strRec, vBuf, strRecDetail
intfileH = FreeFile()
Open "c:\test\text1.txt" For Input As #intfileH
strBuf = Input(LOF(intfileH), #intfileH)
Set rst = CurrentDb.OpenRecordset("tblNames")
vBuf = Split(strBuf, "#")
For Each strRec In vBuf
If strRec <> "" Then
strRecDetail = Split(strRec, vbCrLf)
With rst
.AddNew
!MyName = strRecDetail(0)
!age = Split(strRecDetail(1), ":")(1)
!Info = Split(strRecDetail(2), ":")(1)
.Update
End With
End If
Next
rst.Close
Close (intfileH)
End Sub
And for the second data, much the same, this will work:
Sub Import2()
Dim intfileH As Integer
Dim strBuf As String
Dim rst As DAO.Recordset
Dim vBuf, strRec
Dim i As Integer
intfileH = FreeFile()
Open "c:\test\text2.txt" For Input As #intfileH
strBuf = Input(LOF(intfileH), #intfileH)
Set rst = CurrentDb.OpenRecordset("tblNames")
vBuf = Split(strBuf, vbCrLf)
For i = 0 To UBound(vBuf)
If vBuf(i) <> "" Then
With rst
.AddNew
!MyName = vBuf(i)
i = i + 2
!age = Split(vBuf(i), " ")(2)
i = i + 1
!Info = vBuf(i)
.Update
End With
End If
i = i + 1
Next
rst.Close
Close (intfileH)
End Sub

Related

How to fix 'Index was outside of bounds of the array'

Using visual basic. Trying to load a series of reports onto a listview, listview consists of 3 columns (location, date and severity level) everytime it loads it crashes due to 'index being outside the bounds of the array'.Specifically around DOI = reportdetails(1) in my code. It is loading off of a textfile. I have the data within the textfile so I am unsure of why it is saying I am asking for information that doesnt exist. The program also encypts the textfile.
Dim locate, DOI, SeverityLevel, ReportTitles, EReportTitles, ReportDetails(2) As String
Dim Index As Integer 'Define Variables
Dim FileNum As Integer = FreeFile()
Dim IncidentReport As ListViewItem
lstReports.Items.Clear()
If Dir("ReportTitles.txt") <> "" Then 'If the directory of the file exits then continue
FileOpen(FileNum, "ReportTitles.txt", OpenMode.Input) 'open file
Do Until EOF(FileNum) 'Repeat until the end of the file is reached
EReportTitles = "" 'Clear variables, to safeguard against crashes or errors
ReportTitles = ""
EReportTitles = LineInput(FileNum) 'EReportTitles is equal to the current file line
Dim FileName As String = "ReportTitles.txt" 'Define variables
Dim I, C As Integer
Dim Last As Integer = EReportTitles.Length - 1
Dim ThisChar As Char
For I = 0 To Last 'Begin for loop
ThisChar = EReportTitles.Chars(I) 'Decryption of file
C = Asc(ThisChar) Xor 22
ThisChar = Chr(C)
ReportTitles += ThisChar
Next
If ReportTitles <> "" Then
ReportDetails = Split(ReportTitles, ",") 'Split the lines when a "," is encountered
locate = ReportDetails(0) 'Assosciate to relevant value in array
DOI = ReportDetails(1)
SeverityLevel = ReportDetails(2)
IncidentReport = New ListViewItem
IncidentReport.Text = locate 'Add relevant values to IncidentReport ListViewItem variable
IncidentReport.SubItems.Add(DOI)
IncidentReport.SubItems.Add(SeverityLevel)
lstReports.Items.Add(IncidentReport) 'Transfer IncidentReport to listview
Else
End If
Loop
FileClose(FileNum) 'close file
End If
Expected result is to load all of the report location, dates and severity levels onto the listview.
Also sorry about the formatting of this question, i'm new to stack overflow.
There's no point declaring ReportDetails like this:
ReportDetails(2) As String
because that creates an array that you never use. Here:
ReportDetails = Split(ReportTitles, ",")
you are creating a new array anyway and the length of that array will be determined by the number of delimiters in ReportTitles. If you're being told that 1 is an invalid index for that array then that array must only contain 1 element, which means that ReportTitles didn't contain any delimiters.
This is not something that we should have to explain to you because you can easily see it for yourself by debugging and you should ALWAYS debug BEFORE posting here. Set a breakpoint at the top of the code, step through it line by line and examine the state at each step. You can easily see the contents of ReportTitles and ReportDetails and anything else to see whether they are what you expect them to be.
If the point here is to read a CSV file then you really ought to be using the TextFieldParser class. The documentation for that class includes a code example.
This requires .Net Standard 2.1, and so I'm not sure if VB.Net can use the required SpanAction for the String.Create() method, but if it is supported it should greatly outperform the original.
lstReports.Items.Clear()
'Read and "Decrypt" (and I use that term loosely) the file with only a single heap allocation
Dim file As String
Using fs As FileStream = File.OpenRead("ReportTitles.txt")
file = String.Create(fs.Length, fs,
Sub(chars, stream)
For i As Integer = 0 To stream.Length - 1
'THIS IS NOT ENCRYPTION! At best, it's obfuscation.
chars(i) = Chr(fs.ReadByte() Xor 22)
Next
End Sub)
End Using
'Use an actual CSV parser
Using reader As New StringReader(file), _
parser As New TextFieldParser(reader)
parser.TextFieldType = FileIO.FieldType.Delimited
parser.Delimiters = New String() {","}
Dim row As String()
While Not parser.EndOfData
row = parser.ReadFields()
If row.Length >= 3 Then
Dim IncidentReport As New ListViewItem()
IncidentReport.Text = row(0) '
IncidentReport.SubItems.Add(row(1))
IncidentReport.SubItems.Add(row(2))
lstReports.Items.Add(IncidentReport)
End If
End While
End Using
If you are not able to use that version, this is not quite as good, but still a better approach than the original:
lstReports.Items.Clear()
'Load and "Decrypt" the file
Dim file As String
Using fs As FileStream = File.OpenRead("ReportTitles.txt")
Dim builder As New StringBuilder(fs.Length)
For i As Integer = 0 To fs.Length - 1
'THIS IS NOT ENCRYPTION! At best, it's obfuscation.
builder.Append(Chr(fs.ReadByte() Xor 22))
Next
file = builder.ToString()
End Using
'Use an actual CSV parser
Using reader As New StringReader(file), _
parser As New TextFieldParser(reader)
parser.TextFieldType = FileIO.FieldType.Delimited
parser.Delimiters = New String() {","}
Dim row As String()
While Not parser.EndOfData
row = parser.ReadFields()
If row.Length >= 3 Then
Dim IncidentReport As New ListViewItem()
IncidentReport.Text = row(0) '
IncidentReport.SubItems.Add(row(1))
IncidentReport.SubItems.Add(row(2))
lstReports.Items.Add(IncidentReport)
End If
End While
End Using
In both cases, use Try/Catch rather than Dir() to check whether the location exists. Just try to open the file. Dir() costs an extra disk seek, and there are precious few things in programming slower than disk I/O.

Read Table of contents using vba

I am trying to read a table of contents in a word document without reading the page numbers. I want to read the table and save it into an array. Coding is not my strong suit so apologies in advance if this question is directed to the wrong area. I have the following piece of code which I found inline, which reads the table and the page numbers but I can't work out how to just read the table.
Dim sourceDocument As Document
Set sourceDocument = ActiveDocument
Dim myField As Field
For Each myField In sourceDocument.TablesOfContents(1).Range.Fields
Debug.Print myField.result.Text ', Chr(13), "-") & " " & " Type: " & myField.Type
DoEvents
Next
I would appreciate any help with this.
Thanks,
Robbie
This should get you on your way:
Public Function GetTOCItems(Optional ByVal fromDocument As Document = Nothing) As Variant
If fromDocument Is Nothing Then _
Set fromDocument = ActiveDocument
Dim toc As TableOfContents
Set toc = fromDocument.TablesOfContents(1)
toc.IncludePageNumbers = False
Dim tocText As Variant
tocText = toc.Range.Text
toc.IncludePageNumbers = True
GetTOCItems = Split(tocText, Chr(13))
End Function
And you can call it like this:
Dim tocItems as Variant
tocItems = GetTOCItems

Getting Multi Rows in Database and transferring it in a multiline textbox in VB.net WinForms

Here in my code, i have a database which has table of my applicants. As you will see in the code below, i want to get the number of rows from my command text and transfer it to the string "abc"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
myr.Close()
mycom.Connection = cn
mycom.CommandText = "SELECT Count(Cellphone) FROM tbl_applicant where Gender='Female';"
myr = mycom.ExecuteReader
Dim abc As String
If myr.Read Then
abc = myr(0)
End If
myr.Close()
On the code Below i used the abc as the number of data i must acquire. Then i used the new query to get the values i wanted to and transfer them to a String Array, as you can see I Redim the universal variable Numb to abc to have its array boundery.
mycom.CommandText = "SELECT Cellphone FROM tbl_applicant where Gender='Female';"
myr = mycom.ExecuteReader
ReDim Numb(abc)
If myr.Read Then
For i As Integer = 1 To abc.ToString - 1
LOT = myr(0).ToString
LOT = LOT + (myr(i).ToString + ",") <- this is where i get the error it says that index is our of range.
Numb = LOT.Split(",")
Next
End If
In this code below, i want the values of Variable Numb() to be transferred to a multiline textbox
Dim sbText As New System.Text.StringBuilder(500)
For i As Integer = 0 To Numb.Length - 2
' This will convert the number to a string, add it to the stringbuilder
' and then append a newline to the text buffer
sbText.AppendLine(Numb(i))
Next i
' Now move the buffer into the control
TextBox1.Text = sbText.ToString()
End Sub
The end value i must see in the textbox should be like
11111111111
11111111112
11111111113
11111111114
and so forth, please try to understand the numbers i am referring it to real phone numbers. Any help with the problem or solution maybe.. Thanks
I don't think you need to first query the db to get the count of records before then going back to the db to get the phonenumbers, you could just do this:
mycom.CommandText = "SELECT Cellphone FROM tbl_applicant where Gender='Female';"
myr = mycom.ExecuteReader
While myr.Read()
TextBox1.Text = TextBox1.Text & myr(0) & Environment.NewLine
End While
No need for array's or List's
While this is just a rough guide and an attempt at understanding your issue, try the code and see if it works for you.

Getting an error (3163) on MS Access 2003

The error says "The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data."
The database is supposed to pull in information from the Excel sheet that is passed through to it, and import the information into a recordset of the text field. However, the text field, somewhere down the line, has been limited to 50 characters. How can I change the maximum size of the text field? Thank you for any help
This is just part of the code, and the textfield I'm trying to make larger is "Idea_#", which is the last line of the code i posted
Sub Read_Recommendations()
On Error GoTo error_code
Dim FD As Office.FileDialog
Dim xlapp As Excel.Application
Dim xlsheet As Excel.Worksheet
Dim xlbook As Excel.Workbook
Dim db As Database
Dim rs As Recordset
Dim sql As String
Dim WP As String
Dim row As Integer
Dim File As String
Set db = CurrentDb
Set FD = Application.FileDialog(msoFileDialogOpen)
If FD.Show = True Then
File = FD.SelectedItems(1)
Set xlapp = CreateObject("Excel.Application")
Set xlbook = GetObject(File)
Set xlsheet = xlbook.Worksheets("Recommendation Approval Form")
Dim protection As Boolean
With xlsheet
'support unprotected worksheets
protection = xlsheet.ProtectContents
If protection Then xlsheet.Unprotect "veproject"
WP = .Range("WP_Number")
' Check that active WP and the WP of the uploading form is the same
' If WPs are different, awares users and prompts user whether or not to continue
Dim DifferentProject As String
If Not get_WP = WP Then
DifferentProject = MsgBox("You are uploading to the project with WP number: " & WP & " which is not the active project. Do you wish to continue?", vbYesNo)
If DifferentProject = 7 Then Exit Sub
End If
' Check that WP is correct by checking if it exists in the Record Information table
' delete the existing recomendations, we want to keep the most recent recomendations
' perhaps change this to a dialog in the future
sql = "DELETE * from tbl_recomendations WHERE WP_Number = '" & WP & "'"
db.Execute (sql)
row = 8
Set rs = db.OpenRecordset("tbl_recomendations")
Do While .Range("D" & row) <> ""
rs.AddNew
rs("WP_Number") = WP
rs("Idea_#") = (.Range("C" & row))
........
In Access, open tbl_recomendations in Design View. It sounds like the Field Size property for Idea_# is set at 50. You can change that up to 255.
If you need to store more than 255 characters in Idea_#, change its Data Type from Text to Memo.

Invalid Qualifier for String.Add in Outlook VBA

You all have been so helpful, and I was wondering whether I might trouble you a bit more. I have nearly completed my conversion from VB.net to VBA for Outlook, and in order to complete that, I need some information on what exactly a particular piece of code is returning. If you all can help out with that, the problem may go away; if not, I might need some help on this invalid qualifier error.
From what I understand, I declare an 'array' in VBA with a command like this:
Dim Computers(1, 1) As String
Which produces a 2x2 array. I then try to fill it like this:
Computers.Add ComputerName, ErrorState
where ComputerName and ErrorState are variables which I have already filled. This results in the error. I will provide you with the entire relevant section below. I need to know how many relevant items are in the outlook inbox, which means checking if they were sent on today's date and by the correct sender. I need this in order to get the correct dimensions on the array Computers. (The array is filled in right now as I know the correct dimensions, but in practise I will not.) I took a piece of code which I found through google, the Scripting Dictionary output, but I do not fully understand it. I need just the number of emails, without any irrelevant text, and I was hoping that the debug line would be able to tell me which command I would need to return the number and nothing else. Unfortunately, because of the above error, I cannot get to this line. Even by stepping through the code, the very first thing it tells me is that there is a problem here. The entire relevant section is below. I know that the formatting is problematic, but I have only been working with VB.NET for 4 days, and this is my second day of working with VBA, so I do not quite have everything down yet. There's some irrelevant stuff in here, I'm pretty sure, but I do not have the experience to make the call of whether something is relevant or not, so I left it all. Sorry for the length!
Private Sub Main()
Dim objOutlook As Outlook.Application
Dim Inbox As Outlook.MAPIFolder
Dim InboxItems As Outlook.Items
Dim Mailobject As Object
Dim strDate As String
Dim ComputerName As Object
Dim ErrorState As Object
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim SenderEmail As String
Dim Computers(1, 1) As String
Dim compLength As Integer
Dim disabledList As Collection
Dim enabledList As Collection
Dim unknownList As Collection
Dim notpresentList As Collection
Dim problemList As Collection
Dim cArrayLength As Integer
Dim I As Integer
Dim J As Integer
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim EmailCount As Integer
Dim compArray() As String
'\\ load csv declarations
Dim file_name As String
Dim fnum As Integer
Dim whole_file As String
Dim lines As Variant
Dim one_line As Variant
Dim num_rows As Long
Dim num_cols As Long
Dim R As Long
Dim C As Long
Set disabledList = New Collection
Set enabledList = New Collection
Set unknownList = New Collection
Set notpresentList = New Collection
Set problemList = New Collection
'\\\\\
'\\Retrieve info from outlook, add to sorted list Computers
'\\\\\
objOutlook = CreateObject("Outlook.Application")
Inbox = objOutlook.GetNamespace("Mapi").GetDefaultFolder(6)
InboxItems = Inbox.Items
InboxItems.SetColumns ("SentOn")
Dim myItems As Outlook.Items
Dim dict As Object
Dim msg As String
Set dict = CreateObject("Scripting.Dictionary")
myItems.SetColumns ("SentOn")
EmailCount = InboxItems.Count
For Each Mailobject In InboxItems
strDate = GetDate(Mailobject.SentOn)
If Not dict.Exists(strDate) Then
dict(strDate) = 0
End If
dict(strDate) = CLng(dict(strDate)) + 1
Next Mailobject
'\\ need redo to assign number of objects to CompLength
msg = ""
For Each o In dict.Keys
msg = msg & o & ": " & dict(o) & " items" & vbCrLf
Next
Debug.Print msg
For Each Mailobject In InboxItems
ComputerName = Mailobject.Subject
ErrorState = Mailobject.Body
strDate = GetDate(Mailobject.SentOn)
SenderEmail = Mailobject.SenderEmailAddress
If strDate = DateToday And SenderEmail = "itadmin#email.org" Then
'\\ Syntax is (key, value)
Computers.Add ComputerName, ErrorState
End If
'MsgBox(Mailobject.Subject)
'MsgBox(Mailobject.SenderName)
'MsgBox(Mailobject.To)
'MsgBox(Mailobject.Body)
Next Mailobject
This website has been incredibly helpful as not only a place for me to ask questions but also as a place for me to find relevant information without having to trouble you all. Unfortunately, it is all too often that I do have to trouble you all, but every time you have been very kind and helpful. And I would like to thank you for that.
you're trying to use the Add() method from a Collection to assign an element in an array. To assign an element in a 2-D array you'd use arr(a,b)=someValue where a and b are numeric values. – Tim Williams
Question with no answers, but issue solved in the comments

Resources