saving userform inputs in an array - arrays

I'm trying to use userforms in word VBA to save an undefined number of variables into an array to later input in a document but I can't get the incremental counter to work and it will only save the last input and it is saved as input 0.
Public i As Integer
Sub Macro6()
UF1.Show
End Sub
Private Sub btnAddC_Click()
Dim CName(100) As String
Dim CAddress(100) As String
CName(i) = txtName.Text
CAddress(i) = txtAddress.Text
i = i + 1
Unload Me
UF1.Show
End Sub
Private Sub btnNext_Click()
Dim CName(100) As String
Dim CAddress(100) As String
Dim n As Integer
CName(i) = txtName.Text
CAddress(i) = txtAddress.Text
Unload Me
For n = 0 To i
Selection.TypeText Text:="Client number " & n & " is " & CName(n) & "."
Selection.TypeParagraph
Selection.TypeText Text:="Client number " & n & " is " & CAddress(n) & "."
Selection.TypeParagraph
Next
End Sub
Private Sub UserForm_Initialize()
txtName.Text = ""
txtAddress.Text = ""
End Sub
The output is always:
Client number 0 is a.
Client number 0 is b.

Related

How to vary the length of a combination of bounds based on the length of an array

I have this script in VBA and I need to apply it to different paths that I need to split. Each path is different in length and has several slash delimiters (/) separating it.
If I exceed the number of elements in the array in the LBound function, an error is returned to me.
Question
How do I dynamically combine this pattern based on length.
Example with 3 elements
That is, if I have an initial array of this type
"category / subcategory / product"
I have to get
"category; category> subcategory; category> subcategory> product"
I have many paths of this type, but sometimes they are composed of 3 parts, other times 4, 5 or even more. This is my starting VBA.
Public Sub TestMe()
Dim strFolderString As String
Dim arrFolderString As Variant
Dim result As String
Dim lenght As Integer
strFolderString = "category\subcategory\product\CustomerName\ProductName\2017\"
arrFolderString = Split(strFolderString, "\")
lenght = UBound(arrFolderString)
result = _
arrFolderString(LBound(arrFolderString) + 1) & ";" & _
arrFolderString(LBound(arrFolderString) + 1) & " > " & _
arrFolderString(LBound(arrFolderString) + 2) & ";" & _
arrFolderString(LBound(arrFolderString) + 1) & " > " & _
arrFolderString(LBound(arrFolderString) + 2) & " > " & _
arrFolderString(LBound(arrFolderString) + 3)
Debug.Print result
End Sub
You may try the following approach to get the dynamic path infos by a tricky loop restricting the inner loop to the current outer value:
Sub PathInfo()
'1) define path input
Dim strFolderString As String
strFolderString = _
"category\subcategory\product\CustomerName\ProductName\2017\"
'remove end slash
strFolderString = Replace(strFolderString & "\", "\\", "")
'2) split parts into array
Dim arrFolderString As Variant
arrFolderString = Split(strFolderString, "\")
'3) Provide for sufficient elements in results array
Dim lastIndex As Long: lastIndex = UBound(arrFolderString)
Dim results(): ReDim results(0 To lastIndex)
'4) Join Path infos
Dim i As Long, j As Long
For i = 0 To lastIndex
Dim delim As String: delim = ""
For j = 0 To i ' << restrict inner loop to i :-)
Dim tmp As String
results(i) = tmp & delim & arrFolderString(j)
delim = ">"
Next j
tmp = results(i)
Next
'5) Show Result
Debug.Print Join(results, ";" & vbNewLine)
End Sub
Results in VB Editors immediate window
category;
category>subcategory;
category>subcategory>product;
category>subcategory>product>CustomerName;
category>subcategory>product>CustomerName>ProductName;
category>subcategory>product>CustomerName>ProductName>2017

New array dimension on break line

I'm putting data from the clipboard into my array and splitting it by new lines. But I also need a second dimension splitted by tabs, but don't know how? The data in clipboard is supposed to have a fixed size, so the number of parts will be the same for each line.
What I have so far
Private Sub btnPaste_Click()
Dim Clipboard As MSForms.DataObject
Dim arrClip As Variant
Dim i As Long
Dim str As String
Dim msg As String
On Error GoTo ERRORHAND
Set Clipboard = New MSForms.DataObject
Clipboard.GetFromClipboard
str = Clipboard.GetText(1)
arrClip = Split(str, vbLf)
For i = LBound(arrClip) To UBound(arrClip)
msg = msg & arrClip(i) & vbLf
Next
MsgBox (msg)
Exit Sub
ERRORHAND:
If Err <> 0 Then Debug.Print Err.Description
End Sub
This gives me an array with new elements on each new line from clipboard, but I don't know how to add elements to a second dimension on each 'tab' found in clipboard?
Example of data in clipboard and how I want it to fill the array
Data in clipboard
Data00 Data10 Data20 Data30
Data01 Data11 Data21 Data31
Data02 Data12 Data22 Data32
Data03 Data13 Data23 Data33
etc...
Should be corresponding array element
Array(0,0) Array(1,0) Array(2,0) Array(3,0)
Array(0,1) Array(1,1) Array(2,1) Array(3,1)
Array(0,2) Array(1,2) Array(2,2) Array(3,2)
Array(0,3) Array(1,3) Array(2,3) Array(3,3)
etc...
This is your code with some adds (hope it helps)
Sub btnPaste_Click()
Dim Clipboard As MSForms.DataObject
Dim arrClip As Variant
Dim i As Long
Dim str As String
Dim msg As String
Dim arrClip2 As Variant
Dim arrClipBid() As Variant
Dim ii As Integer
'On Error GoTo ERRORHAND
Set Clipboard = New MSForms.DataObject
Clipboard.GetFromClipboard
str = Clipboard.GetText(1)
arrClip = Split(str, vbLf)
ReDim arrClipBid(LBound(arrClip) To UBound(arrClip), 0 To 0)
For i = LBound(arrClip) To UBound(arrClip)
arrClip2 = Split(arrClip(i), Chr(9))
If MaxLen < UBound(arrClip2) Then
MaxLen = UBound(arrClip2)
ReDim Preserve arrClipBid(LBound(arrClip) To UBound(arrClip), 0 To MaxLen)
End If
For ii = LBound(arrClip2) To UBound(arrClip2)
arrClipBid(i, ii) = arrClip2(ii)
msg = msg & "(" & i & ", " & ii & ")" & arrClip2(ii)
Next ii
msg = msg & vbLf
Next
MsgBox (msg)
Exit Sub
ERRORHAND:
If Err <> 0 Then Debug.Print Err.Description
End Sub

I keep getting and error message 'Index was outside the bounds of the array'

I am trying to display information from a text file into a multiline textbox. I run the code but the system displays an error message 'Index was outside the bounds of the array'. There are no obvious error messages and I can't seem to manipulate the code to get rid of this problem. Take a look:
Public Class TeachCon
Dim layout As String
Dim Contacts(6) As Details
Structure Details
Dim Name As String
Dim Email As String
Dim RoomNum As String
Dim number1, number2 As Integer
End Structure
Sub LoadTeachContacts(ByRef Contacts() As Details)
Dim TextFile As String = "\\Sjcdom01\mstudent\LHeywood\documents\A2\Computing\Comp 4 - Smail\Project\Text Files\Teacher Contact List.txt"
Dim TextLine As String = ""
Dim ArrayCounter As Integer = 0
Dim objReader As New System.IO.StreamReader(TextFile)
'loop through text file and load all contacts
Do While objReader.Peek() <> -1
'read next line from file
TextLine = TextLine & objReader.ReadLine() & vbNewLine
'declare an array and use it to split line from file
Dim TempArray() As String = Split(TextLine, ",")
'transfer each array element into the appropriate part of the contacts stucture
Contacts(ArrayCounter).Name = TempArray(0)
*Contacts(ArrayCounter).Email = TempArray(1)*
Contacts(ArrayCounter).RoomNum = TempArray(2)
Contacts(ArrayCounter).number1 = TempArray(3)
Contacts(ArrayCounter).number2 = TempArray(4)
'empty string before reading next line from file
TextLine = ""
'increment array counter
ArrayCounter = ArrayCounter + 1
Loop
End Sub
Private Sub ButShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim ArrayCounter As Integer = 0
LoadTeachContacts(Contacts)
Do Until ArrayCounter = 3
layout = Contacts(ArrayCounter).Name & "," & Contacts(ArrayCounter).Email & "," & Contacts(ArrayCounter).RoomNum & "," & Contacts(ArrayCounter).number1 & "," & Contacts(ArrayCounter).number2
If ArrayCounter = 0 Then
TextBox7.Text = layout
End If
ArrayCounter += 1
Loop
End Sub
End Class
The text enclosed by the * is where the system says it is outside the bounds of the array.
Well, one of your lines probably splits into an array that is shorter than you expect, and hence the index does not exist. Check the length of the array before you get the value. Maybe something like this
If TempArray.Length > 0 Then Contacts(ArrayCounter).Name = TempArray(0)
If TempArray.Length > 1 Then Contacts(ArrayCounter).Email = TempArray(1)
If TempArray.Length > 2 Then Contacts(ArrayCounter).RoomNum = TempArray(2)
If TempArray.Length > 3 Then Contacts(ArrayCounter).number1 = TempArray(3)
If TempArray.Length > 4 Then Contacts(ArrayCounter).number2 = TempArray(4)
Don't know exactly what your TextFile contains in it. But inorder to handle the exception change the code as below
'declare an array and use it to split line from file
Dim TempArray() As String = Split(TextLine, ",")
'transfer each array element into the appropriate part of the contacts stucture
If TempArray.Length > 0 Then
Contacts(ArrayCounter).Name = TempArray(0)
*Contacts(ArrayCounter).Email = TempArray(1)*
Contacts(ArrayCounter).RoomNum = TempArray(2)
Contacts(ArrayCounter).number1 = TempArray(3)
Contacts(ArrayCounter).number2 = TempArray(4)
End If
'empty string before reading next line from file
TextLine = ""
It would be helpful if you could give the content of the file also:
"\Sjcdom01\mstudent\LHeywood\documents\A2\Computing\Comp 4 - Smail\Project\Text Files\Teacher Contact List.txt"
I think that you should check if the line is empty or not, because the item 0 will be available without error as a Null String, but the item 1 will throw 'Index was outside the bounds of the array' In LoadTeachContacts Sub
'read next line from file
If objReader.ReadLine().Trim = "" Then Continue Do
TextLine = TextLine & objReader.ReadLine() & vbNewLine

access vba copy select statement to array

I'm a beginner with VBA and I'm wondering how to copy a select statement to array. how can i do?
ı tried to do something but i couldn't complite.
Private Sub Komut485_Click()
Dim a() As String
'Dim a() As Integer
'abc = Me.talep_kayit_no.Value
'MsgBox abc
For sayac = 1 To 5
a(sayac) = "SELECT [3_gh_odemeler].[gh_no] FROM 3_gh_odemeler WHERE [3_gh_odemeler].[gh_no] =" & Me.talep_kayit_no.Value & ";"
sayac = sayac + 1
MsgBox a(1)
Next
End Sub
I thought arrays always start at 0 and would therefore use the first position(0) as the right position.
Dim intArraySize as integer
dim a() as string
intArraySize =5
redim a(intArraySize)
For sayac = 0 To intArraySize
a(sayac-1) = "SELECT [3_gh_odemeler].[gh_no] FROM 3_gh_odemeler WHERE [3_gh_odemeler].[gh_no] =" & Me.talep_kayit_no.Value & ";"
sayac = sayac + 1
MsgBox a(1)
Next
End Sub

Aligning Array Output in Rich Text Box

I am working on the same program as a previous question, but now I am having trouble aligning the output of my now-fixed program. I know some of it might look messed up, but somehow I got it to work.
Whatever the case, the output is unaligned with my headings and doesn't look good. I cannot figure out how to fix this.
Imports System.IO
Imports System.Convert
Public Class frmAll
'Declare Streamreader
Private objReader As StreamReader
'Declare arrays to hold the information
Private strNumber(24) As String
Private strName(24) As String
Private strSize(24) As String
Private decCost(24) As Integer
Private Sub frmAll_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Set objReader
objReader = New StreamReader("products.csv")
Call FillArray()
End Sub
Private Sub FillArray()
'Declare variables and arrays
Dim decCost(24, 1) As Decimal
Dim strFields() As String
Dim strRec As String
Dim intCount As Integer = 0
Dim chrdelim As Char = ToChar(",")
'Set strRec to read the lines
strRec = objReader.ReadLine
'Do while loop to fill array.
Do While strRec <> Nothing
strFields = strRec.Split(chrdelim)
strNumber(intCount) = strFields(0)
strName(intCount) = strFields(1)
strSize(intCount) = strFields(2)
decCost(intCount, 0) = ToDecimal(strFields(3))
decCost(intCount, 1) = ToDecimal(strFields(4))
'Set strRec to read the lines again
strRec = objReader.ReadLine
'increment the index
intCount += 1
Loop
Call Calculate(decCost)
End Sub
Private Sub Calculate(ByVal numIn(,) As Decimal)
'Define arrays to hold total cost
Dim decRowTotal(24) As Decimal
'Define variables to hold the counters for rows and columns
Dim intR As Integer
Dim intC As Integer
'Calcualte total cost
For intC = 0 To 1
For intR = 0 To 24
decRowTotal(intR) += numIn(intR, intC) * 1
Next
Next
Call Output(numIn, decRowTotal)
End Sub
Private Sub Output(ByVal NumIn(,) As Decimal, ByVal RowTotalIn() As Decimal)
Dim strOut As String
Dim intR As Integer = 0
Dim intC As Integer = 0
strOut = "ID" & vbTab & "Item" & vbTab & vbTab & vbTab & "Size" & vbTab & vbTab & vbTab & vbTab & "Total Price" &
vbCrLf & "--------------------------------------------------------------------------------------------------------------------------------------------------" &
vbCrLf
For intC = 0 To 24
strOut &= strNumber(intC) & vbTab
strOut &= strName(intC) & vbTab
strOut &= strSize(intC) & vbTab & vbTab
strOut &= RowTotalIn(intC).ToString("c")
strOut &= vbCrLf
Next
rtbAll.Text = strOut
End Sub
End Class
You are using the wrong tool for this kind of work.
You need a DataGridView instead of a RichTextBox.
With a DataGridView you can adjust the column size at your will.
The approach of using tabs to create pseudocolumns inside the richtextbox fails because, if some text (the item column for example) is longer than the space used to represent a tab, then the next tab will shift to a rightmost position and throughout the rest of the line the text is misaligned.
You can try to minimize the problem adding or removing tabs, but, unless the text pixel length equals the length reserved for your tabs, your columns will be misaligned.
In the link provided below you will find an example of a simple unbound datagridview filled with string data.
http://msdn.microsoft.com/en-us/library/5s3ce6k8(v=vs.100).aspx

Resources