Find the last textbox with value in userform...VBA

RobbieC

Active Member
Joined
Dec 14, 2016
Messages
376
Office Version
  1. 2010
Platform
  1. Windows
Hi there, I have a userform with 10 text input fields.

Each is named txt1 txt2 txt3.... txt10

The user can enter info into any of the boxes, but not necessarily all of them...

When the user clicks the UPDATE button, it creates a string of the values and inserts a comma if <>"" :

Code:
Dim TotalString As String
TotalString = ""
Dim txtVar As String


Dim txtNumVar(1 To 10) As String


For i = 1 To 10
    txtVar = "txt" & i
    txtNumVar(i) = Me.Controls(txtVar).Value
    If txtNumVar(i) <> "" Then txtNumVar(i) = ", " & txtNumVar(i)
    TotalString = TotalString & (txtNumVar(i))
Next
This all works fine, but I'd like to replace the final comma in the final TotalString with " and"

Code:
TotalString = TotalString (find last "," and replace with " and")

If you can point me in the right direction, I'd be very grateful

Thanks
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
Afternoon,

does this not start the TotalString with ", " ? Is that working as intended?

Regardless, theres probably a few ways to do this.

You could, InStrRev to find the last comma position, then Replace (", " with " and ") and add it onto a Left of the string up to the comma position.

Code:
Dim commaPos As Long
commaPos = InStrRev(TotalString, ",")
if commapos > 0 then TotalString = Replace(TotalString, ", ", Left(TotalString, commaPos - 1) & " and ", commaPos)
 
Upvote 0

Forum statistics

Threads
1,215,219
Messages
6,123,681
Members
449,116
Latest member
HypnoFant

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top