How can 2 Character instead of 1 in My Textbox? - vb.net

My problem is very simple. this code works only on txtDraw (Letter) & Y.
Example: txtDrawA1, txtDrawA2, and so on. I want to make this code work as follows: txtDrawAA1, txtDrawAA2, replacing a character to be 2 characters.
This Code: Dim tbName = "txtDraw" & Chr(64 + x) & y
Private Sub txtDrawSum()
On Error Resume Next
For y = 1 To 8
Dim sum = 0
For x = 16 To 30
Dim tbName = "txtDraw" & Chr(64 + x) & y
sum += CInt(Tab3.TabPages(1).Controls(tbName).Text)
Next
TabControl2.TabPages(4).Controls("SumDrawA" & (0 + y)).Text = sum.ToString()
Next
End Sub

Well, the simple solution would just be to repeat Chr(64 + x) twice i.e.:
Dim tbName = "txtDraw" & Chr(64 + x) & Chr(64 + x) & y
but a better approach would be to use the String constructor:
Dim tbName = "txtDraw" & New String(Chr(64 + x), 2) & y
or Strings.StrDup:
Dim tbName = "txtDraw" & StrDup(2, Chr(64 + x)) & y
This is better because say suddenly you want to repeat the character 10 times, you wouldn't have to duplicate the code as in the first example.
As an aside, you might want to use string interpolation to clean up the concatenations:
Dim tbName = $"txtDraw {StrDup(2, Chr(64 + x))} {y}"

Try using the replace function.
OldString.ToString().Replace("txtDrawA","txtDrawAA")

Related

Operation with two string textboxes separated by a comma vb net

I have 2 strings of numbers: like this:
Textbox1.Text = 1,2,3,4,5,6,7,8,9,11
Textbox2.Text = 11,9,8,7,6,5,4,3,2,1
I want to calculate, display in textbox3, their sum, + or - or * or /
all value from textbox1.text + all values from textbox2.text
Textbox3.Text = 12,11,11,11,11,11,11,11,11,12
I would like, though, and a specification where I can change the sign, instead of + being -, or / or * depending on my choice.
this code is a bit cumbersome, I would like to improve it with something simpler.
Dim str1 As String
'Set your string value
str1 = TxtBoxLstDrawsPlus.Text
Dim str2 As String
'Set your string value
str2 = TxtBoxLstDrawsMinus.Text
Dim strWords As String() = str1.Split(",")
Dim strWordsAAA As String() = str2.Split(",")
TextBox6.Text &= Val(strWords(0)) + Val(strWordsAAA(0)) & "," & Val(strWords(1)) + Val(strWordsAAA(1)) & "," & Val(strWords(2)) + Val(strWordsAAA(2)) & "," & Val(strWords(3)) + Val(strWordsAAA(3)) & "," & Val(strWords(4)) + Val(strWordsAAA(4)) & "," & Val(strWords(5)) + Val(strWordsAAA(5)) & "," & Val(strWords(6)) + Val(strWordsAAA(6)) & "," & Val(strWords(7)) + Val(strWordsAAA(7)) & "," & Val(strWords(8)) + Val(strWordsAAA(8)) & "," & Val(strWords(9)) + Val(strWordsAAA(9)) & "," & Val(strWords(10)) + Val(strWordsAAA(10)) & "," & Val(strWords(11)) + Val(strWordsAAA(11)) & "," & Val(strWords(12)) + Val(strWordsAAA(12)) & "," & Val(strWords(13)) + Val(strWordsAAA(13)) & "," & Val(strWords(14)) + Val(strWordsAAA(14)) & "," & Val(strWords(15)) + Val(strWordsAAA(15)) & "," & Val(strWords(16)) + Val(strWordsAAA(16)) & "," & Val(strWords(17)) + Val(strWordsAAA(17)) & "," & Val(strWords(18)) + Val(strWordsAAA(18)) & "," & Val(strWords(19)) + Val(strWordsAAA(19))
You can split the input strings (TextBox1.Text and TextBox2.Text), Zip the string arrays to produce a result array, and finally String.Join it in TextBox3:
Here's in one line:
TextBox3.Text = String.Join(",", TextBox1.Text.Split({","c}, StringSplitOptions.RemoveEmptyEntries).
Zip(TextBox2.Text.Split({","c}, StringSplitOptions.RemoveEmptyEntries),
Function(x, y) CInt(x) + CInt(y)))
You can use the same approach to do different arithmetic operations:
Dim opr As Char = "+"c '<- From your arithmetic operation selector like ComboBox.
TextBox3.Text = String.Join(",", TextBox1.Text.Split({","c}, StringSplitOptions.RemoveEmptyEntries).
Select(Function(x) CInt(x)).
Zip(TextBox2.Text.Split({","c}, StringSplitOptions.RemoveEmptyEntries).
Select(Function(y) CInt(y)),
Function(x, y)
Select Case opr
Case "-"c
Return x - y
Case "*"c
Return x * y
Case "/"c
Return x \ y
Case Else
Return x + y
End Select
End Function))
It'll be a good idea if you'd validate your inputs first:
Dim Arr1() = TextBox1.Text.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Dim Arr2() = TextBox2.Text.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Dim opr As Char = OprTextBox.Text.ElementAtOrDefault(0) 'A TextBox this time as another example.
Dim ValidOpr() As Char = {"+"c, "-"c, "*"c, "/"c}
If Arr1.Length <> Arr2.Length OrElse
Arr1.Any(Function(x) Not Integer.TryParse(x, Nothing)) OrElse
Arr2.Any(Function(x) Not Integer.TryParse(x, Nothing)) OrElse
Not ValidOpr.Contains(Opr) Then
MessageBox.Show("Excuse me ... !?!?")
Return
End If
'You have valid inputs. Proceed...
TextBox3.Text = String.Join(",", Arr1.Select(Function(x) CInt(x)).
Zip(Arr2.Select(Function(x) CInt(x)),
Function(x, y)
Select Case opr
Case "-"c
Return x - y
Case "*"c
Return x * y
Case "/"c
Return x \ y
Case Else
Return x + y
End Select
End Function))
Better yet, enum the arithmetic operations:
Public Enum ArithmeticOperations
Add
Subtract
Multiply
Divide
End Enum
.. and create a parameterized Function that returns the joined string.
'You name it...
Public Function GetCalcString(input1 As String,
input2 As String,
opr As ArithmeticOperations) As String
Dim Arr1() = input1.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Dim Arr2() = input2.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
If Arr1.Length <> Arr2.Length OrElse
Arr1.Any(Function(x) Not Integer.TryParse(x, Nothing)) OrElse
Arr2.Any(Function(x) Not Integer.TryParse(x, Nothing)) Then
Return Nothing
End If
Return String.Join(",", Arr1.Select(Function(x) CInt(x)).
Zip(Arr2.Select(Function(x) CInt(x)),
Function(x, y)
Select Case opr
Case ArithmeticOperation.Subtract
Return x - y
Case ArithmeticOperation.Multiply
Return x * y
Case ArithmeticOperation.Divide
Return x \ y
Case Else
Return x + y
End Select
End Function))
End Function
Assuming that, the arithmetic operations are listed in a ComboBox in the same order:
Private Sub TheCaller()
TextBox3.Text = GetCalcString(TextBox1.Text,
TextBox12.Text,
CType(ComboBox1.SelectedIndex, ArithmeticOperations))
End Sub

VBA, 2nd last "/" using InstrRev

I have code that parses out the last word on a string.
ie. Stack/Over/Flow will give me "Flow".
But I want to get "Over/Flow".
This is what I got, but only able to get "Flow"
arr(counter - 2) = "'" & mid(Text, InStrRev(Text, "/") + 1) & "'"
I would use Split()
Sub lastTwo()
Dim str As String
str = "Stack/Over/Flow"
Dim splt() As String
splt = Split(str, "/")
If UBound(splt) > 0 Then
Debug.Print splt(UBound(splt) - 1) & "/" & splt(UBound(splt))
End If
End Sub
Here is a function that does it:
Function lastParts(str As String, delim As String, x As Long) As String
Dim splt() As String
splt = Split(str, "/")
If UBound(splt) + 1 >= x Then
Dim t As String
t = "=INDEX(INDEX({""" & Join(splt, """;""") & """},N(IF({1},ROW(" & UBound(splt) - x + 2 & ":" & UBound(splt) + 1 & "))),),)"
lastParts = Join(Application.Transpose(Application.Evaluate(t)), delim)
Else
lastParts = str
End If
End Function
It has three parts, the string, the delimiter and the number of returns.
It can be called using your code:
arr(counter-2) = lastParts(Text,"/",2)
or from the worksheet
=lastParts(A1,"/",2)
Initially misread the question. You can nest InStrRev() calls
arr(counter - 2) = "'" & mid(Text, InStrRev(Text, "/",InStrRev(Text, "/")-1)+1) & "'"

How to print N number of primes in Visual basic (forms)?

I have this visual basic code to receive user input and print out that many primes. For instance if a user inputs 5, the output should be: 1, 3, 5, 7, 11. But I found difficulty with it.Here is my code:
Dim i, n, input, currentPrime As Integer
Dim Wrap As String = Chr(10) & Chr(13)
input = txtInput.Text
currentPrime = 1
txtAns.Text = "Prime Numbers are : " & Wrap
Do While (currentPrime <= input)
For i = currentPrime To input
For j = 2 To Fix(i / 2) + 1
If i Mod j = 0 Then
n = 1
End If
Next
If n = 1 Then
n = 0
Else
txtAns.Text = txtAns.Text & Wrap & i & " is a prime number " & Wrap
End If
Next
currentPrime += 1
Loop
Try this...
Dim i, n, input As Integer
Dim Wrap As String = Chr(10) & Chr(13)
input = txtInput.Text
Dim found = 0
Dim output = "Prime Numbers are : " & Wrap
While found < input
i = i + 1
For j = 2 To Fix(i / 2) + 1
If i Mod j = 0 Then
n = 1
End If
Next
If n = 1 Then
n = 0
Else
output = output & Wrap & i & " is a prime number " & Wrap
found = found + 1
End If
End While
txtAns.Text = output

Read Each line not reading through entire file

I am using Vb to take a .txt file, parse it, and check for errors. My code works just fine, however, the code does not go through the entire file. It stops, on average, 20 lines shy of the EOF.
I am using the following
For Each lines As String In System.IO.File.ReadLines(myFile)
from here I parse the line and see if it needs any fixes.
Is there something that I'm missing or something that just cant be avoided.
The files that I'm reading in are about 150,000 KB to 230,000 KB and over 2 million lines.
As requested, the following is my code. Warning, I just started using Vb...
Module Module1
Sub Main()
Dim root As String = "C:\Users\mschramm\Documents\Agco\WindSensor\Data\filestobecleaned\"
Dim datafile As String = root & "ES.txt"
Dim outfile As String = root & "temptry.txt"
Dim output As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(outfile, False)
Dim k As UInteger = 0
Dim fixes As UInteger = 0
Dim time As ULong = 0
Dim count As UInteger = 0
Dim n As UInteger = 0
Dim LineCount As UInteger = 0
Dim TimeStep As ULong = 100
Dim Solar As UInteger = 0
For Each lines As String In System.IO.File.ReadLines(datafile)
LineCount = LineCount + 1
'Console.WriteLine(LineCount)
Dim parsedline As String() = Split(lines, ",")
If IsNumeric(parsedline(0)) = True And UBound(parsedline) = 8 Then
'TimeStep = parsedline(0) - time
Solar = parsedline(1)
time = parsedline(0)
output.WriteLine(lines & " Good Line")
count = count + 1
Else
Dim j As UInteger = 0
Dim ETX As Integer = 0
Dim STX As Integer = 0
Dim datacheck As Boolean = False
Dim fixedline As String = ""
Dim newtime As ULong = 0
For j = 0 To UBound(parsedline)
Dim a As Char = parsedline(j)
If a = (Chr(3)) Then ETX = j
If a = (Chr(2)) Then STX = j
Next
j = 0
If (STX < ETX) And (ETX - STX) = 6 And STX >= 2 Then
If Len(parsedline(STX + 1)) = 8 And Len(parsedline(STX + 2)) = 8 And Len(parsedline(STX + 3)) = 8 Then
Dim g = Len(parsedline(STX - 2))
While (j < g) And datacheck = False
If IsNumeric(parsedline(STX - 2)) Then
If parsedline(STX - 2) - time < 10000 And parsedline(STX - 2) - time > 0 Then
newtime = Right(parsedline(STX - 2), Len(parsedline(STX - 2)))
Solar = parsedline(STX - 1)
'TimeStep = newtime - time
fixedline = newtime & "," & parsedline(STX - 1) & "," & parsedline(STX) & "," & parsedline(STX + 1) & "," & parsedline(STX + 2) & "," & parsedline(STX + 3) & "," & parsedline(STX + 4) & "," & parsedline(STX + 5) & "," & parsedline(STX + 6) & " Fixed Line"
datacheck = True
Else
j = j + 1
parsedline(STX - 2) = Right(parsedline(STX - 2), Len(parsedline(STX - 2)) - 1).ToString
End If
Else
j = j + 1
parsedline(STX - 2) = Right(parsedline(STX - 2), Len(parsedline(STX - 2)) - 1).ToString
End If
End While
End If
End If
If (STX < ETX) And (ETX - STX) = 6 And STX = 0 Then
If Len(parsedline(1)) = 8 And Len(parsedline(2)) = 8 And Len(parsedline(3)) = 8 And Len(parsedline(4)) = 1 And Len(parsedline(5)) = 2 And Len(parsedline(6)) = 3 Then
newtime = time + TimeStep
fixedline = newtime & "," & Solar & "," & parsedline(STX) & "," & parsedline(STX + 1) & "," & parsedline(STX + 2) & "," & parsedline(STX + 3) & "," & parsedline(STX + 4) & "," & parsedline(STX + 5) & "," & parsedline(STX + 6) & " Fixed Line Gave Time and Solar"
datacheck = True
End If
End If
If newtime < time And newtime > 1000 Then
Dim badtime As ULong = newtime
Dim firstdig As ULong = time
Dim loopcount As UInteger = 0
While firstdig > 9
firstdig = firstdig / 10
loopcount = loopcount + 1
End While
firstdig = firstdig * (10 ^ loopcount)
If (firstdig + badtime) > time Then
newtime = firstdig + badtime
If (newtime - (10 ^ loopcount)) > time Then
newtime = newtime - (10 ^ loopcount)
End If
End If
End If
If datacheck = True Then
k = k + 1
If (newtime > 500) Then
output.WriteLine(fixedline)
'count = count + 1
time = newtime
End If
End If
If datacheck = False Then
n = n + 1
If STX >= 0 And ETX > 0 And ETX - STX < 9 Then
Console.WriteLine(LineCount)
'n = n + 1
End If
End If
End If
Next
Console.WriteLine(count & " Good lines")
Console.WriteLine(k & " Lines Corrected")
Console.WriteLine(LineCount & " Total Lines")
Console.WriteLine(n & " Lines were thrown out")
Console.WriteLine(n / LineCount * 100 & "% thrown out")
End Sub
End Module
and here is a sample of the data
Time: 16:52:18.0
Date: 11/6/2014
Time,Sensor1,U,V,W
544161,219,Q,-001.341,+000.947,+000.140,M,00,17
544284,218,Q,-001.207,+001.074,+000.225,M,00,1C
544361,220,Q,-000.935,+000.898,+000.187,M,00,17
544460,220,Q,-001.299,+001.151,-000.009,M,00,17
This is what the last 10 lines look like
Q,+001.681,-003.510,-0356154697,236,Q,+000.826,-002.744,-000.559,M,00,19
Q,+000.474,-002.789,-0356155062,234,Q,+000.400,-002.975,+000.438,M,00,1D
Q,+000.813,-002.934,-0356155297,236,Q,+000.146,-002.129,-000.235,M,00,16
Q,+000.494,-002.234,+0356155497,236,Q,+000.681,-001.996,-000.248,M,00,1F
Q,+000.800,-001.999,-0356155697,236,Q,+001.181,-002.883,-000.795,M,00,1A
356156060,233,Q,+000.400,-002.106,+000.251,M,00,18
356156296,235,Q,+000.888,-001.026,+000.442,M,00,10
356156495,236,Q,+000.570,-001.694,+000.589,M,00,13
356156695,236,Q,+001.495,-002.177,-000.035,M,00,15
356157060,234,Q,+000.770,-003.484,-000.161,M,00,14
for this file, the code makes it to the 6th to last line.
Thanks to mafafu for pointing out the solution.
I never closed the file, so the addition of output.Close() fixed everything.
Once again, thank you mafafu.

Best VBA Approach in Access for Median of a Dataset

I am a novice in access and VBA. I have a function that I use to calculate the median. The current function acts as a Domain function and uses all data to calculate the median rather than the dataset that makes up the rest of the query/report. I would like to know how to modify this code or a better approach to find the median of dataset used to create the report.
Option Compare Database
Option Explicit
Function DMedian(tName As String, fldName As String) As Single
Dim MedianDB As DAO.Database
Dim ssMedian As DAO.Recordset
Dim RCount As Integer, i As Integer, x As Double, y As Double, _
OffSet As Integer
Set MedianDB = CurrentDb()
Set ssMedian = MedianDB.OpenRecordset("SELECT [" & fldName & _
"] FROM [" & tName & "] WHERE [" & fldName & _
"] IS NOT NULL ORDER BY [" & fldName & "];")
'NOTE: To include nulls when calculating the median value, omit
'WHERE [" & fldName & "] IS NOT NULL from the example.
ssMedian.MoveLast
RCount% = ssMedian.RecordCount
x = RCount Mod 2
If x <> 0 Then
OffSet = ((RCount + 1) / 2) - 2
For i% = 0 To OffSet
ssMedian.MovePrevious
Next i
DMedian = ssMedian(fldName)
Else
OffSet = (RCount / 2) - 2
For i = 0 To OffSet
ssMedian.MovePrevious
Next i
x = ssMedian(fldName)
ssMedian.MovePrevious
y = ssMedian(fldName)
DMedian = (x + y) / 2
End If
If Not ssMedian Is Nothing Then
ssMedian.Close
Set ssMedian = Nothing
End If
Set MedianDB = Nothing
End Function
If you are referring to calculating the median against a custom report that you have created, then simply save your query and pass the query name in to 'tname' instead of a table name.