VB .net - Linenumber Issue - vb.net

I'm doing a bit of code that pulls through rows from a database connection and should return a linenumber for each row. I'm doing this in the following way.
linenum = 0
Do While (rsData.Read())
linenum = linenum + 1
Now when I ouput a DB connection with 8 rows, the linenumbers for each of the rows return as 1222222.
I need to determine the correct numbers so I can do the following to change row styles.
If ((linenum / 2) = Int(linenum / 2)) Then
html += Chr(13) & "<tr class=""openrow2"">"
Else
html += Chr(13) & "<tr class=""openrow1"">"
End If
Any ideas why my rows past the first one seem to only get referred to as linenumber 2 rather than the next number in the series?
Thanks!

Just a shoot in the dark, but where is your loop statement ?
Also if linenum is an integer why don't use the MOD operator ?
linenum = 0
Do While rsData.Read()
linenum = linenum + 1
If (linenum Mod 2) = 0) Then
html += Chr(13) & "<tr class=""openrow2"">"
Else
html += Chr(13) & "<tr class=""openrow1"">"
End If
....
Loop

Related

Treat last element differently when concatenating strings

I made a loop for concatenating strings:
For cz As Integer = 0 To length - 1 Step +1
result += GetChar(a, index) + " * 2^" & length - 1 & " + "
index += 1
length -= 1
Next cz
Is it possible to not add the "+" on the loop's last step?
I want to use some operations on that result but when i have "+" as last char I can't.
String.Join will accomplish that for you if you pass it an enumerable of strings:
Dim result = String.Join(" + ",
a.Select(Function (c, i) c & " * 2^" & (a.Length - 1 - i)))

How can I extract the 'logical_test' from an if statement in excel?

I'm putting together an excel spreadsheet for calculations, and I need to be able to show the formulas to go with the decisions, for the most part its pretty straight forward, but When I come to an 'if' formula in an excel cell, I don't want to show the value_if_true and value_if_false... Just the logical_test value.
Example:
Formula is: =if(and(5<=A1, A1<=10),"Pass", "Fail");
Result will be: "and(5<=A1, A1<=10)"
I need to be able to work with complex logical tests which may include nested if statements, so just splitting at the commas won't work reliably. Similarly the value_if_true and value_if_false statements could also contain if statements.
Any ideas?
If have clear understanding of what you asking for, then you can use something like this (shall be used only with IF() statement :
Function extrIf(ByVal ifstatement As Range) As String
Dim S$, sRev$, x%, k
S = Replace(Replace(ifstatement.Formula, "IF(", "\"), "),", ")|")
sRev = StrReverse(S)
If InStr(1, sRev, "|") > InStr(1, sRev, "\") Or InStr(1, sRev, "|") = 0 Then
x = InStr(1, StrReverse(Left(sRev, InStr(1, sRev, "\"))), ",") - 1
S = Mid(S, 1, Len(S) - InStr(1, sRev, "\") + x) & "|"
End If
sRev = ""
For Each k In Split(S, "|")
If k <> "" Then
If k Like "*\*" Then
sRev = sRev & ", " & Mid(k, InStr(1, k, "\") + 1, 999)
End If
End If
Next
extrIf = Mid(sRev, 3, 999)
End Function
example:
test:
Maybe this is not complete solution for you, but I think it might give you right direction.
If the cell formula starts with an If statement then you can return the logic test (starting after the first open parenthesis) by determining the position of the first comma where the sum of the previous open parenthesis - the sum previous closed = 0.
Formulas
Function ExtractIfTest(Target As Range) As String
Dim ch As String, s As String
Dim openP As Long
Dim x As Long
s = Target.formula
For x = 5 To Len(s)
ch = Mid(s, x, 1)
If Mid(s, x, 1) = "(" Then
openP = openP + 1
ElseIf Mid(s, x, 1) = ")" Then
openP = openP - 1
ElseIf Mid(s, x, 1) = "," And openP = 0 Then
ExtractIfTest = Mid(s, 5, x - 12)
End If
Next
End Function
Results
There might be instances where the is a comma without parenthesis A1,B1. If this happens simple escape them with parenthesis (A1,B1)
I've written an UDF that extract any of the parameters of the target formula. It's close to the one in Thomas answer, but more global and takes into account strings that can enclose commas or parenthesis.
Function ExtractFormulaParameter(Target As Range, Optional Position As Long = 1) As Variant
Dim inString As Boolean
Dim formula As String
Dim st As Long, sp As Long, i As Long, c As String
Dim parenthesis As Long, comma As Long
formula = Target.formula
st = 0: sp = 0
If Position <= 0 Then ExtractFormulaParameter = CVErr(xlErrValue): Exit Function
For i = 1 To Len(formula)
c = Mid$(formula, i, 1)
If inString Then
If c = """" Then
inString = False
End If
Else
Select Case c
Case """"
inString = True
Case "("
parenthesis = parenthesis + 1
If parenthesis = 1 And Position = 1 Then
st = i + 1
End If
Case ")"
parenthesis = parenthesis - 1
If parenthesis = 0 And sp = 0 Then sp = i: Exit For
Case ","
If parenthesis = 1 Then
comma = comma + 1
If Position = 1 And comma = 1 Then sp = i: Exit For
If Position > 1 And comma = Position - 1 Then st = i + 1
If Position > 1 And comma = Position Then sp = i: Exit For
End If
Case Else
End Select
End If
Next i
If st = 0 Or sp = 0 Then
ExtractFormulaParameter = CVErr(xlErrNA)
Else
ExtractFormulaParameter = Mid$(formula, st, sp - st)
End If
End Function
By default it returns the first parameter, but you can also return the second or the third, and it should work with any formula.
Thanks for the replies all. I thought about this more, and ended up coming up with a similar solution to those posted above - essentially string manipulation to extract the text where we expect to find the logical test.
Works well enough, and I'm sure I could use it to extract further logical tests from substrings too.

Excel VBA - dropping and adding zeros in a specified character count

I am attempting to build a vba code to build txt files that we use to test with. I am running into an issue. Some of my results will have .00 which I made dropped off using Str = Str & "00" & Left(CashRightJust(Range("h63"), 11), 9)
This basically is telling it to look at cell H63, right justified the amount but left justify the end by 9 to drop cents if it is "00".
My problem is we now need to test for it to have actual change like .25. Using this code alone adds a zero at the end of the change. I need to adjust this code to reflect if it is more then .00 do not edit or add zeros
I hope this makes sense. I am still fairly new at this and have gotten pretty far but there are still some moments I am lost. Thank you.
Spreadsheet created to build code to send to txt file
Function Detail_Rec1()
Dim strlencount As Integer
Dim strspacer As Integer
If Range("b63").Value <> "5" Then
Exit Function
End If
Str = Str & Range("b63").Value **Result: 5**
Str = Str & Range("c63").Value **Result: 400**
Str = Str & Range("d63").Value **Result: 1234567**
Str = Module1.SpaceAdd(Str, 1) **Result: 1 space**
Str = Str & Trim(Range("e63").Value)
strlencount = Len(Trim(Range("e63").Value))
strspacer = 30 - strlencount
Str = Module1.SpaceAdd(Str, strspacer) **Result: Company name with spacefill for 30 character; name is left justified**
Str = Str & Trim(Range("f63").Value)
strlencount = Len(Trim(Range("f63").Value))
strspacer = 11 - strlencount
Str = Module1.SpaceAdd(Str, strspacer) **Result: Company ID number; left justify; space filled total 11 characters**
Str = Str & Range("G63").Value Result: 116
Str = Str & CashRightJust(Range("h63"), 11) **Result: 1000; only 1000 no cents; dollars only; 11 character zero filled right justify**
Str = Str & CashRightJust(Range("i63"), 11)**Result: 1000; only 1000 no cents; dollars only; 11 character zero filled right justify**
Str = Str & CashRightJust(Range("j63"), 11)**Result: 1000; only 1000 no cents; dollars only; 11 character zero filled right justify**
Str = Str & Trim(Range("k63").Value)
strlencount = Len(Trim(Range("k63").Value))
strspacer = 4 - strlencount
Str = Module1.ZeroAdd(Str, strspacer) **Result: Rate of 4 characters entered; 4 character length**
Str = Module1.SpaceAdd(Str, 1) **Result: 1 space**
Str = Str & CashRightJust(Range("l63"), 11) **Result: 3348.75 needs to be 334875. 11 characters, right justified, no decimal.**
Str = Str & CashRightJust(Range("m63"), 11)
Str = Str & CashRightJust(Range("n63"), 11)
Str = Str & CashRightJust(Range("o63"), 11)
Str = Str & "00000" & Right(Range("p63").Value, 6)
strlencount = Len(Trim(Range("p63").Value))
strspacer = 6 - strlencount
Str = Module1.ZeroAdd(Str, strspacer)
[Excel image of line being coded][How text file should appear][2]2]
My end result for what I need is
23.45 - 2345
23.00 - 2300 unless the spec is saying dollars only then it needs to be 23
No rounding.
I hope this helps out more with the visuals
Added Info: My module that is used for the $ amts currently is following:
If Str = 0 Then
CashRightJust = ZeroAdd(Str2, c)
Exit Function
Else
If InStr(Str, ".") > 0 Then
Str2 = Right(Str, 2)
If InStr(Str2, ".") > 0 Then
strnew = Str & "0"
Else
strnew = Str
End If
Else
strnew = Str & "00"
End If
Excel snapshot of info being coded
54001234567 Bob's Tires 987654321 116000000010000000000005000000009503525 00000334875
This is how it is coming out:
54001234567 Bob's Tires 987654321 1160000010000000000005000000000950003525 000334875
I could not post the image of the txt file I don't have enough reputations; sorry; this is how it should appear
Can you try something like this? It assumes your entire string is in cell A1 and that this is the situation where dollars and cents are not required (I assume you can handle the situation where they are because it sounds like you more or less leave the string alone in that case).
lenOfStr = 11
newStr = ""
subStr = Right(Cells(1, 1), lenOfStr)
If Right(subStr, 2) = "00" Then 'we need to keep these
lenOfStr = 9
End If
foundLeftmost = False
For i = 1 To lenOfStr
If Mid(subStr, i, 1) <> "0" and Mid(subStr, i, 1) <> "." Then
newStr = newStr & Mid(subStr, i, 1) 'start collecting for the new string
foundLeftmost = True
End If
If foundLeftmost and Mid(subStr, i, 1) <> "." Then 'need to include zeros that may show up in the middle of the substring
newStr = newStr & Mid(subStr, i, 1)
End If
Next i
subStr = newStr
The end result is stored in subStr. Hopefully I understood your problem correctly. Let me know if I didn't.

VB - comparing numbers in two labels

I'm doing a school project in Visual Basic (using visual studio 2015) and i'm kinda stuck.
My goal is to create a lottery, where player chooses 6 numbers from checkboxes, then he generates six random numbers (1 - 49) and finally, those two sets should be compared and needed result is the number of correctly guessed numbers.
I have both results (guessed numbers, generated numbers) saved in two different labels.
The checkboxes itself are genereted like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lev = 20
tt = 0
For j = 1 To 50
tt = tt + 1
n = n + 1
box(j) = New CheckBox
box(j).Name = "box(" & Str(j) & ")"
If n = 11 Then lev = lev + 110 : n = 1 : tt = 1
box(j).Left = lev
box(j).Parent = Me
box(j).Top = tt * 20
box(j).Tag = j
box(j).Text = j
box(j).Visible = True
Next
box(50).Enabled = False
End Sub
First label (guessed numbers) is filled this way (i'm not posting whole code)
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + " " + box(j).Text
Next
and the second one (generated numbers) like this:
Do
rn = rg.Next(1, 50)
If Not r.Contains(rn) Then
r.Add(rn)
End If
Loop Until r.Count = 6
Label1.Text = r(0).ToString + " " + r(1).ToString + " " + r(2).ToString + " " + r(3).ToString + " " + r(4).ToString + " " + r(5).ToString
any idea how to compare numbers stored in those labels and get the result (number of correctly guessed numbers).
thanks in advance
You can compare numbers in the labels by splitting the Text properties of the labels into arrays of strings and converting them to integer arrays. First though there is a tiny problem with your code that adds the guessed numbers to the label.
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + " " + box(j).Text
Next
The " " should be moved to the end of the line because at the moment, the label will always start with a space and that messes with the function below. So you should have -
For j = 1 To 50
If box(j).Checked = True Then Label9.Text = Label9.Text + box(j).Text + " "
Next
Ok. The function below splits the two text labels into their own array and loops through the guesses and checks if any number is contained in the generated numbers. It then returns the number of matches.
Private Function ComparePicks() As Integer
Dim numbersMatched As Integer
Dim picks(5) As Integer
Dim generatedNumbers(5) As Integer
For i As Integer = 0 To 5
picks(i) = CInt(Split(Label9.Text, " "c)(i))
Next
For i As Integer = 0 To 5
generatedNumbers(i) = CInt(Split(Label1.Text, " "c)(i))
Next
For i As Integer = 0 To 5
If generatedNumbers.Contains(picks(i)) Then
numbersMatched += 1
End If
Next
Return numbersMatched
End Function

Issues with For Loop in VB

For i = 1 To 5
If i = 0 Then
i = i + 1
ElseIf i Mod 2 = 0 Then
LabelEvens.Text = i
i = i + 1
Else
LabelOdds.Text = i
i = i + 1
End If
Next i
I'm making a program in VB where I have to use a for loop to sort between 2 numbers(loop limit 1 and 2) and find if they are even or odd, Then output the results to 2 labels. This loop makes sense to me, but for example when I put in 1 and 4 all it outputs is a 5 in the odd label. I guess my question is can anyone see the issue with my loop?
You don't need to add 1 to your loop variable i manually, the for loop itself does that for you behind the scenes:
For i = 1 To 5
If i Mod 2 = 0 Then
LabelEvens.Text = i
Else
LabelOdds.Text = i
End If
Next i
You'll noticed I've also removed the If i = 0 bit since i can never be zero within that loop. It ranges from one to five inclusive.
One other thing you'll need to do is to append the value to your text box. What you have at the moment is a replacement so that it'll only be set to the last value processed. Something like this should suffice:
' Initialise to empty strings '
LabelEvens.Text = ""
LabelOdds.Text = ""
' Append the values '
For i = 1 To 5
If i Mod 2 = 0 Then
LabelEvens.Text = LabelEvens.Text & "," & CStr(i)
Else
LabelOdds.Text = LabelOdds.Text & "," & CStr(i)
End If
Next i
' Remove initial comma from both '
LabelEvens.Text = Mid(LabelEvens.Text,2)
LabelOdds.Text = Mid(LabelOdds.Text,2)
Some issues in your code:
For i = 1 To 5
If i = 0 Then <-- 'I' will never be 0 since you start from 1
i = i + 1 <-- Don't manually increment since you are using a for
ElseIf i Mod 2 = 0 Then
LabelEvens.Text = i
i = i + 1 <-- Don't manually increment since you are using a for
Else
LabelOdds.Text = i
i = i + 1 <-- Don't manually increment since you are using a for
End If
Next i
Another issue you have is that if you have more than one odd number in the for range (say in a range of 1 to 10) you will only get the last number. What do you want to do in this case? Concatenate all odd numbers in a string or stop after the first one is found? Do you really need a FOR loop at all?
you can Also state
LabelEvens.Text="" 'Clear contents of the label before assigning new values
LabelOdds.Text=""
For i As Integer = 1 To 5
If i Mod 2 = 0 Then
LabelEvens.Text = LabelEvens.Text & i
Else
LabelOdds.Text = LabelOdds.Text & i
End If
Next
From Above you can replace '&' with '+' if you want the Total.