radomly add strings to this code i have - vb6

text1.text = "Mayweather vs McGregor: Los Angeles Press Conference"
text2.text returns count of space.
my custom value say = "love"
now on each button click , i want to randomly add that custom string to each position the space.
so first click
text1.text = "Mayweather vs love McGregor: Los Angeles Press Conference"
second click
text1.text = "Mayweather vs McGregor: ;love Los Angeles Press Conference"
and so on depending on the code were it detects the space then add it their only once per click.
Code:
Dim Count As Integer
Dim i As Integer
For i = 1 To Len(Text1.Text)
If Mid(Text1.Text, i, 1) = " " Then Count = Count + 1
Text2.Text = Count
Next

Here is a small test project:
Option Explicit
' 1 form with:
' 2 textbox controls: name=Text1 and name=Text2
' 1 command button : name=Command1
Private mstrText As String
Private Sub Command1_Click()
Static intCount As Integer 'declare as static to remember value of intCount on next click
Dim intLoop As Integer
Dim intSpace As Integer
intCount = intCount + 1
'find correct space
intLoop = 0
intSpace = 0
Do While intLoop < intCount
intSpace = InStr(intSpace + 1, mstrText, " ")
intLoop = intLoop + 1
Loop
Text1.Text = Left$(mstrText, intSpace) & "love " & Mid$(mstrText, intSpace + 1)
Caption = CStr(intSpace)
End Sub
Private Sub Form_Load()
mstrText = "Mayweather vs McGregor: Los Angeles Press Conference"
Text1.Text = mstrText
End Sub
Private Sub Text1_Change()
'show number of spaces
Dim intSpace As Integer
intSpace = Len(Text1.Text) - Len(Replace(Text1.Text, " ", ""))
Text2.Text = CStr(intSpace)
End Sub
Is this what you mean?

Related

Need help fixing Exception Unhandled

I am getting the following error:
System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string.
Parameter name: length'
(Look for Bold Italic on code *** that's where it is taking me to fix that)
Not sure what the problem is. Here is the whole code:
Imports GroceryApp.GroceryItem
Imports System.IO
Public Class GroceryItemForm
Private strFileName As String = String.Empty
Private Sub btnAddToBasket_Click(sender As Object, e As EventArgs) Handles btnAddToBasket.Click, AddToolStripMenuItem.Click
Dim gi As GroceryItem
Dim price As Double
' Validate that brand name is entered
If txtBrandName.Text = "" Then
MsgBox("Please input an Brand Name", , "Value Required")
txtBrandName.Focus()
Exit Sub
End If
' Validate that price is entered
If Not Double.TryParse(numPrice.Text, price) Then
MsgBox("Please input an Price", , "Value Required")
numPrice.Focus()
Exit Sub
End If
' Validate that Aisle is selected
If cboAisle.Text = "" Then
MsgBox("Please select an Aisle", , "Value Required")
cboAisle.Focus()
Exit Sub
End If
***txtScanNumber.Text = txtBrandName.Text.Substring(0, 3) & "1019"***
gi = New GroceryItem(txtScanNumber.Text, txtBrandName.Text, price)
gi.Type = [Enum].Parse(GetType(Aisle), cboAisle.Text)
gi.Description = txtDescription.Text
basket.Add(gi)
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
Private Sub ViewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewToolStripMenuItem.Click
'Dim result As String = ""
'Dim i As Integer = 1
'For Each gi As GroceryItem In basket
'result = result & "Item " & i & vbNewLine & "Aisle: " & gi.Type.ToString & vbNewLine & "Scan Number: " & gi.ScanNumber & vbNewLine & "Brand Name: " & gi.BrandName & vbNewLine & vbNewLine
'i = i + 1
'Next
'MsgBox(result, , "Basket Details")
Dim oForm As BasketDisplayForm
oForm = New BasketDisplayForm()
oForm.Show()
oForm = Nothing
End Sub
Private Sub GroceryItemForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oForm As LoginForm
oForm = New LoginForm()
oForm.Show()
oForm = Nothing
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim rowLine As String = ""
'If strFileName = String.Empty Then
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
strFileName = SaveFileDialog1.FileName
Dim fsStream As New FileStream(strFileName, FileMode.Append, FileAccess.Write)
Dim sw As New StreamWriter(fsStream)
Dim sb As New System.Text.StringBuilder
For Each Item As GroceryItem In basket
sb.AppendLine(String.Concat(Item.ScanNumber, ",", Item.Type.ToString, ",", Item.BrandName, ",", Item.Description, ",", Item.Price))
'rowLine = rowLine + Item.ScanNumber + "," + Item.Type.ToString + "," + Item.BrandName + "," + Item.Description + "," + Item.Price.ToString
Next
'IO.File.WriteAllText(strFileName, sb.ToString)
'rowLine = rowLine.Remove(rowLine.Length - 1, 1)
sw.WriteLine(sb)
sw.Flush()
MsgBox("Data Saved Successfully")
sw.Close()
basket.Clear()
End If
'End If
End Sub
Private Sub LoadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoadToolStripMenuItem.Click
Dim basketFile As StreamReader
Dim gi As GroceryItem
Dim sNo, brand, desc, aisle As String
Dim price As Double
Dim y As Integer
basket.Clear()
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
strFileName = OpenFileDialog1.FileName
basketFile = File.OpenText(strFileName)
' Read Power rating from file
Using sr As StreamReader = New StreamReader(strFileName)
Do While sr.Peek() > -1
For Each c As String In sr.ReadToEnd().Split(CType(Chr(10), Char))
sNo = ""
For Each d As String In c.Split(",")
If y = 0 Then
sNo = d
End If
If y = 1 Then
aisle = d
End If
If y = 2 Then
brand = d
End If
If y = 3 Then
desc = d
End If
If y = 4 Then
price = d
End If
y += 1
Next
If (sNo <> "") Then
gi = New GroceryItem(sNo, brand, price)
gi.Type = [Enum].Parse(GetType(Aisle), aisle)
gi.Description = desc
If (sNo <> "" & vbCr & "") Then
basket.Add(gi)
End If
End If
y = 0
Next
Loop
End Using
basketFile.Close()
End If
End Sub
End Class

How to filter dates using dtpicker in listview with database

I'm creating a payroll system, and I want to search the date in listview using dtpicker and calculate the number of daily rate,Please help me guys
Private Sub sumBtn_Click()
Dim objItem As ListItem
Dim iCounter As Integer
Dim lngDailyRate As Long
Dim iDateSubitemIndex As Integer
Dim iDailyRateSubitemIndex As Integer
iDateSubitemIndex = 6
iDailyRateSubitemIndex = 7
For iCounter = 1 To Listview1.ListItems.Count
' Get List Item
Set objItem = Listview1.ListItems.Item(iCounter)
' Check Date
If CDate(objItem.SubItems(iDateSubitemIndex)) >= DTPicker3 And CDate(objItem.SubItems(iDateSubitemIndex)) >= DTPicker4 Then
lngDailyRate = lngDailyRate + CLng(objItem.SubItems(iDailyRateSubitemIndex))
End If
Next
MsgBox "Daily Rate for " & DTPicker3 & " to " & DTPicker4 & " is " &
lngDailyRate
End Sub
Here's how you can sum up your DAILY_RATE column using just the data in the ListView:
Private Sub Command1_Click()
Dim objItem As ListItem
Dim iCounter As Integer
Dim lngDailyRate As Long
Dim iDateSubitemIndex As Integer
Dim iDailyRateSubitemIndex As Integer
' Update these to reflect your ListView
iDateSubitemIndex = 1
iDailyRateSubitemIndex = 2
For iCounter = 1 To ListView1.ListItems.Count
' Get List Item
Set objItem = ListView1.ListItems.item(iCounter)
' Check Date
If CDate(objItem.SubItems(iDateSubitemIndex)) = DTPicker1 Then
lngDailyRate = lngDailyRate + CLng(objItem.SubItems(iDailyRateSubitemIndex))
End If
Next
MsgBox "Daily Rate for " & DTPicker1 & " is " & lngDailyRate
End Sub
Please update the two SubitemIndex variables to match the columns in your ListView. These are used to retrieve the data from the correct column.

VB6 Converting a fraction to a decimal and a decimal to fraction

There's a few posts on this, but none seem to provide a whole code solution, so I'm posting this up, which is culled (and credited where appropriate) from various bits and pieces of ideas on the Internet. VB6 doesn't have any function to convert from a fraction to a decimal number, which I needed for a project that I was working on which was concerned with meal recipes. I considered writing a DLL in .NET and plugging it into my application, but decided on this approach in the end. I hope this is useful for others. The solution below will do the following:
You supply a decimal number and you will be returned the fraction as a string.
You supply a fraction as a string and you will be returned with the decimal number.
In both cases, whole numbers are accounted for eg. "2 3/4" (two and three quarters) or "2.75".
I'm sure the code is not efficient, so any improvements are welcome.
Copy/Paste this as a new Class module:
Option Explicit
Private ErrorNote As String
'Properties
Public Property Get GetAsFraction(numToConvert As Double) As String
On Error GoTo GetAsFraction_Error
GetAsFraction = FncGetAsFraction(numToConvert)
On Error GoTo 0
Exit Property
GetAsFraction_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'GetAsFraction' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Property
Public Property Get GetAsDecimal(fractionString As String) As Double
On Error GoTo GetAsDecimal_Error
GetAsDecimal = FncGetAsDecimal(fractionString)
On Error GoTo 0
Exit Property
GetAsDecimal_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'GetAsDecimal' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Property
'Functions - private
Private Function FncGetAsDecimal(fractionToConvert As String) As Double
Dim result As Double
Dim wholeNumber As Integer
Dim splitStr As Variant
Dim numerator As Integer
Dim denominator As Integer
Dim fractionString As String
Dim dividedByPos As Integer
On Error GoTo FncGetAsDecimal_Error
splitStr = Split(fractionToConvert, " ")
If UBound(splitStr) = 1 Then
wholeNumber = splitStr(0)
fractionString = splitStr(1)
Else
fractionString = splitStr(0)
End If
dividedByPos = InStr(1, fractionString, "/")
numerator = Left(fractionString, dividedByPos - 1)
denominator = Mid(fractionString, dividedByPos + 1)
result = Val(numerator) / Val(denominator) + wholeNumber
FncGetAsDecimal = result
On Error GoTo 0
Exit Function
FncGetAsDecimal_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'FncGetAsDecimal' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Function
Private Function FncGetAsFraction(numToConvert As Double) As String
Dim result As String
Dim numeratorCount As Integer
Dim denominator As Single
Dim multiplierStr As String
Dim i As Integer
Dim fractionNum As Single
Dim lowestCommonDenominator As Long
Dim wholeNumber As Integer
Dim decimalPos As Integer
On Error GoTo FncGetAsFraction_Error
If numToConvert > 0 Then
decimalPos = InStr(1, CStr(numToConvert), ".")
If decimalPos > 1 Then
wholeNumber = CStr(Mid(numToConvert, 1, decimalPos - 1))
numToConvert = CStr(Mid(numToConvert, decimalPos))
End If
numeratorCount = FncCountDecimalPlaces(numToConvert)
multiplierStr = "1"
For i = 1 To numeratorCount
multiplierStr = multiplierStr & "0"
Next i
fractionNum = numToConvert * Val(multiplierStr)
denominator = 1 * Val(multiplierStr)
result = FncCrunchFraction(fractionNum, denominator)
If result = "" Then result = fractionNum & "/" & denominator
If wholeNumber <> 0 Then result = wholeNumber & " " & result
Else
result = "ERROR"
End If
FncGetAsFraction = result
On Error GoTo 0
Exit Function
FncGetAsFraction_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'FncGetAsFraction' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Function
Private Function FncCountDecimalPlaces(num As Double) As Integer
Dim result As Integer
Dim numberStr As String
Dim i As Integer
Dim decimalPointPos As Integer
On Error GoTo FncCountDecimalPlaces_Error
numberStr = CStr(num)
If Len(numberStr) > 0 Then
i = 1
Do While i <= Len(numberStr) And decimalPointPos = 0
If Mid(numberStr, i, 1) = "." Then decimalPointPos = i
i = i + 1
Loop
End If
If i > 1 Then
result = (Len(numberStr) - i + 1)
End If
FncCountDecimalPlaces = result
On Error GoTo 0
Exit Function
FncCountDecimalPlaces_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'FncCountDecimalPlaces' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Function
'Credit to:
'http://www.tek-tips.com/viewthread.cfm?qid=206890
'dsi (Programmer) - 7 Feb 02 10:38
Private Function FncCrunchFraction(num1 As Single, num2 As Single) As String
Dim num As Single
Dim dem As Single
Dim cnt1 As Integer
Dim cnt2 As Integer
Dim numFactors() As Single
Dim demFactors() As Single
Dim common As Single
Dim i As Integer
Dim j As Integer
On Error GoTo FncCrunchFraction_Error
num = num1
dem = num2
For i = 2 To Int(num / 2) Step 1
If (num Mod i = 0) Then
cnt1 = cnt1 + 1
ReDim Preserve numFactors(1 To cnt1)
numFactors(cnt1) = i
End If
Next i
cnt1 = cnt1 + 1
ReDim Preserve numFactors(1 To cnt1)
numFactors(cnt1) = num
For i = 2 To Int(dem / 2) Step 1
If (dem Mod i = 0) Then
cnt2 = cnt2 + 1
ReDim Preserve demFactors(1 To cnt2)
demFactors(cnt2) = i
End If
Next i
cnt2 = cnt2 + 1
ReDim Preserve demFactors(1 To cnt2)
demFactors(cnt2) = dem
For i = cnt1 To 1 Step -1
For j = cnt2 To 1 Step -1
If (numFactors(i) = demFactors(j)) Then
common = numFactors(i)
FncCrunchFraction = num / common & "/" & dem / common
Exit Function
End If
Next j
Next i
FncCrunchFraction = ""
On Error GoTo 0
Exit Function
FncCrunchFraction_Error:
ErrorNote = "Line:" & Erl & " Number:" & Err.number & " (" & Err.Description & ") in procedure 'FncCrunchFraction' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Function
Then call it with these code examples:
Public Function DecimalToFraction(number As Double) As String
Dim myFractionDecimal As New ClsFractionDecimal
DecimalToFraction = myFractionDecimal.GetAsFraction(number)
Set myFractionDecimal = Nothing
End Function
Public Function FractionToDecimal(fractionString As String) As Double
Dim myFractionDecimal As New ClsFractionDecimal
FractionToDecimal = myFractionDecimal.GetAsDecimal(fractionString)
Set myFractionDecimal = Nothing
End Function

"integer out of range" error in a for next statement

I've gone nuts on this, and I'm sure the error is right in front of me, I just cant see it. appreciate all the help in debugging the statements below.
I have multiple slides in a ppt presentation. in some of the slides, there is a star shape, and a textbox with text "Hold" or "Yearly". I want to change the color of the star only if there is no textbox with "Hold" or "Yearly".
Sub Set_Star_Shape_Color_Green_Test()
Dim PPApp As Object ' As PowerPoint.Application
Dim PPPres As Object ' As PowerPoint.Presentation
Dim PPSlide As Object ' As PowerPoint.Slide
Dim iShpCnt1 As Integer
Dim iShpCnt2 As Integer
Dim iShpCnt3 As Integer
Dim iSlideCnt As Integer
Dim iBoxTopPos As Integer
Dim sHold As String
Dim sStar As String
Dim sTbox As String
Dim sTColor As String
Dim oShp As Shape
Set PPApp = GetObject(, "Powerpoint.Application")
Set PPPres = PPApp.ActivePresentation
Set PPSlide = PPPres.Slides _
(PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)
iShpCnt0 = PPSlide.Shapes.Count
For iShpCnt1 = 1 To iShpCnt0 'PPSlide.Shapes.Count
iBoxTopPos = 260
' iSlideCnt = 2 removed
sHold = ""
sStar = ""
iShpCnt1 = 1
For iShpCnt1 = 1 To PPSlide.Shapes.Count
If iShpCnt1 <= PPSlide.Shapes.Count Then
**Set oSh = PPApp.ActivePresentation.Slides(iSlideCnt).Shapes(iShpCnt1) ' this is where i am getting the integer out of range error**
If oSh.Name.Text Like "*Hold*" Or oSh.Name.Text Like "*Yearly*" Then
sHold = oSh.Name
End If
If oSh.Name Like "*Star*" Then
sStar = oSh.Name
End If
End If
Next
For iShpCnt2 = 1 To iShpCnt0 ' this fixed the error
Set oSh = PPApp.ActivePresentation.Slides(iSlideCnt).Shapes(iShpCnt2)
If oSh.Name Like "*Star*" And sHold = "" Then
oSh.Fill.ForeColor.RGB = RGB(50, 205, 50) ' change the color to green
End If
Next
' go to next slide
If PPSlide.SlideIndex + 1 < PPPres.Slides.Count Then
PPApp.ActiveWindow.View.GotoSlide PPSlide.SlideIndex + 1
Set PPSlide = PPPres.Slides _
(PPApp.ActiveWindow.Selection.SlideRange.SlideIndex + 1)
End If
Next
' Clean up
Set PPSlide = Nothing
Set PPPres = Nothing
Set PPApp = Nothing
End Sub
You are setting the iterator to two.
For iSlideCnt = 1 To PPPres.Slides.Count
iBoxTopPos = 260
iSlideCnt = 2 <--- right here
It will go out of bounds if you have just one slide.

Drop Down & Picture Box integration

I have a simple form with a drop down box with a list of names in it
and a picture box above that .
how can i make it when i select a name the picture
of that person shows up automatically in the picture box ?
use a user defined type containing both the name as well as the picture file, and then create an array of this type
for example :
'1 form with :
' 1 listbox : name=List1
' 1 picturebox : name=Picture1
Option Explicit
Private Type PERSON
strName As String
strPicture As String
End Type
Private mperFriend(4) As PERSON
Private Sub Form_Load()
Dim intIndex As Integer
mperFriend(0).strName = "Bob"
mperFriend(0).strPicture = "Bob.jpg"
mperFriend(1).strName = "Jane"
mperFriend(1).strPicture = "Jane.jpg"
mperFriend(2).strName = "Fred"
mperFriend(2).strPicture = "Fred.jpg"
mperFriend(3).strName = "Iris"
mperFriend(3).strPicture = "Iris.jpg"
mperFriend(4).strName = "John"
mperFriend(4).strPicture = "John.jpg"
List1.Clear
For intIndex = 0 To UBound(mperFriend)
List1.AddItem mperFriend(intIndex).strName
Next intIndex
End Sub
Private Sub List1_Click()
Caption = mperFriend(List1.ListIndex).strPicture
Picture1.Picture = LoadPicture(App.Path & "\" & mperFriend(List1.ListIndex).strPicture)
End Sub

Resources