Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Capitalize First Letter in EVERY SENTENCE in a TextBox 7

Status
Not open for further replies.

CubeE101

Programmer
Nov 19, 2002
1,492
US
For Anyone wondering how to Automatically Capitalize the first Letter of Each sentence as you type in a textbox.

Notes:
Chr(9) is the Tab Key
Cap is the Capital letter for the current key
SP is Starting Point or cursor Position (Textbox.SelStart)
TC is Temporary Character (The character currently being tested)


Basically what this does is:

When you press a key, before it processes the key into the textbox, the following checks are made...
1) Check to see if the cursor is at the front of the line. If so... Capitallize it.
2) Check to see if the Letter before the cursor is a space. If so... Scan backwards to the first of the string to see if a period occurs before any other letter with the ONLY exceptions being a TAB character and Space Character.
3) If a period is found, the current letter is capitalized and terminates the for loop.
4) If a character is found other than a period, space or tab, the loop is terminated, and the character remains at it's current Cap State.
5) If the begining of the string is reached before a period or other character, then the current character is the first non-space/tab character in the string, AKA the begining of a sentence. So... the current Letter is capitalized.
Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
  Cap = Asc(UCase(Chr(KeyAscii)))
  SP = Text1.SelStart
  If SP = 0 Then
    KeyAscii = Cap
  Else
    If Mid(Text1, SP, 1) = " " Or Mid(Text1, SP, 1) = Chr(9) Then
      For i = SP To 1 Step -1
        TC = Mid(Text1, i, 1)
        If TC = "." Then
          KeyAscii = cap
        Else
          If TC <> &quot; &quot; And TC <> Chr(9) Then Exit For
        End If
      Next
      If i < 2 Then KeyAscii = cap
    End If
  End If
End Sub
Sometimes... the BASIC things in life are the best...
cheers.gif

or at least the most fun ;-)
-Josh Stribling
 
Hmmm...
 
Here is a function that I have used to capitalize the first letter of every word in a string. Used mainly for names and addresses.

It also checks for names beginning with 'Mc' or 'Mac' (and a couple others) and correctly capitalizes them.

Use this functioon in the validate or lost focus event of text boxes. Feel free to use as you wish.

Public Function CapAllFirst(Entry As String) As String
'// Capitalize the first letter of all words in the string.
'// Correctly capitalize names beginning with 'Mc' or 'Mac'.
Dim strChar As String, strNewVal As String
Dim intSpot As Integer, intMcMac As Integer
Dim bolNewWord As Boolean

bolNewWord = True
intMcMac = 0
strNewVal = Entry
If strNewVal <> UCase(strNewVal) Then
For intSpot = 1 To Len(Entry) Step 1
strChar = Mid(strNewVal, intSpot, 1)
If strChar = &quot; &quot; Then
bolNewWord = True
Else
If bolNewWord = True Or intMcMac = intSpot Then
If UCase(Mid(strNewVal, intSpot, 2)) = &quot;MC&quot; Or _
UCase(Mid(strNewVal, intSpot, 2)) = &quot;O'&quot; Then
intMcMac = intSpot + 2
ElseIf UCase(Mid(strNewVal, intSpot, 3)) = &quot;MAC&quot; Then
intMcMac = intSpot + 3
ElseIf UCase(Mid(strNewVal, intSpot, 2)) = &quot;RR&quot; Then
intMcMac = intSpot + 1
End If
Mid(strNewVal, intSpot, 1) = UCase(Mid(strNewVal, intSpot, 1))
bolNewWord = False
Else
Mid(strNewVal, intSpot, 1) = LCase(Mid(strNewVal, intSpot, 1))
End If
End If
Next intSpot
End If
CapAllFirst = strNewVal
End Function
Thanks and Good Luck!

zemp
 
Hmmm...
 
Seems like an ideal challenge for regular expressions...
 
lol...
strongm,
what are all the hmmmm....'s about?
Sometimes... the BASIC things in life are the best...
cheers.gif

or at least the most fun ;-)
-Josh Stribling
 
The hmmms are because I'm dubious about both set's of example code.

The first example has issues where a sentence finished with anything other than a fullstop (e.g exclamation mark, question mark). It also won't handle the situation where you go back and insert a full stop into already existing text. It is also a very 'expensive' operation, because of the number of temporary strings it requires (all those Mid functions). Plus, and this is just a personal style issue, none of the variables are declared, so the code is working in variants the whole time.

The second example can be replaced, as JohnYingling points out, with the somewhat shorter StrConv function. Well, except for the name capitalisation element - but getting names correctly capitalised is a somewhat more complex task than the code allows for; there are plenty of surnames that start Mac, for example, that do NOT take a capital immediately afterwards. So the function suffers from the fact that, because it is really trying to treat all words as names, it isn't really good as a general capitalisation routine (for example it will get words like 'machinegun', 'machete' and 'macho' wrong),whilst at the same time not going far enough in the names analysis.

It's your own fault, you asked [wink]

Now, back to regular expressions...
 
What, no-one wants to figure out a RegExp solution?
 
JohnYingling; because when I started with that function I was an absolute newbie and I just haven't bothered to try and update or streamline it.

I like your suggestion, maybe it is about time I tried to use something else. Thanks and Good Luck!

zemp
 
Zemp,

I was worried that you were getting &quot;too clever by half&quot;. I remember when I first saw StrConv(string, vbProper), having proudly converted an old Cobol &quot;Proper&quot; routine to VB, and thinking %^&^@&*#. Forms/Controls Resizing/Tabbing Control
Compare Code (Text)
Generate Sort Class in VB or VBScript
 
OK to correct a few &quot;What if&quot; situations... you can take this base code and make a few modifications to it... this meant to be an example to base YOUR OWN code from...
Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
  Cap = Asc(UCase(Chr(KeyAscii)))
  SP = Text1.SelStart
  If SP = 0 Then
    KeyAscii = Cap
  Else
    If Mid(Text1, SP, 1) = &quot; &quot; Or Mid(Text1, SP, 1) = Chr(9) Then
      For i = SP To 1 Step -1
        TC = Mid(Text1, i, 1)
        If TC = &quot;.&quot;
Code:
or TC = &quot;!&quot;
Code:
 Then
          KeyAscii = cap
        Else
          If TC <> &quot; &quot; And TC <> Chr(9) Then Exit For
        End If
      Next
      If i < 2 Then KeyAscii = cap
    End If
  End If
End Sub[code]

also...
this code will also capitalize the following letter when the period(.), exclamation(!), or semi-colon(;) are pressed.
along with checking for the above mentioned in the text when a different key is pressed.

[code]Private Sub Text1_KeyPress(KeyAscii As Integer)
sp = Text1.SelStart
cap = UCase(Chr(KeyAscii))
Code:
If cap = &quot;.&quot; Or cap = &quot;!&quot; Or cap = &quot;;&quot; Then
  For i = sp + 1 To Len(Text1)
    tc = Mid(Text1, i, 1)
    If tc <> &quot; &quot; And tc <> Chr(8) Then
      Text1.SelStart = i - 1
      Text1.SelLength = 1
      Text1.SelText = UCase(Text1.SelText)
      Exit For
    End If
  Next
Else
Code:
  If sp = 0 Then
    KeyAscii = Asc(cap)
  Else
    If Mid(Text1, sp, 1) = &quot; &quot; Or Mid(Text1, sp, 1) = Chr(9) Then
      For i = sp To 1 Step -1
        tc = Mid(Text1, i, 1)
        If tc = &quot;.&quot;
Code:
 Or tc = &quot;!&quot; Or tc = &quot;;&quot;
Code:
Then
          KeyAscii = Asc(cap)
        Else
          If tc <> &quot; &quot; And tc <> Chr(9) Then Exit For
        End If
      Next
      If i < 2 Then KeyAscii = Asc(cap)
    End If
  End If
Code:
End If
Text1.SelStart = sp
Code:
End Sub

As for being &quot;expensive&quot; most of us are living in the world of Pentium 2's and up (especially if you are using VB) so a couple of temporary strings &quot;Should Not&quot; make a difference.
(if it does... see they they have some GREAT deals that just might fix your problem;-)...J/K)


As for the pre-declareing variables... it is my personal preference NOT to unless required (such as objects), VB does not require you too... it does it for you... so why bother... now if speed were a major concern like when you get into dealing with high speed graphics and rendering... yeah, go ahead and pre-define them otherwise why bother. One of the things I hated about Pascal was having to define everything before you start typeing code...
even C/C++ lets you define on-the-fly... int Temp = 10; ...
so until that applies to VB... you'll probably continue to see my code looking the same... I have been codeing that way for over 10 years now and do not have any intentions of changing. You might catch me using a DEFINT A-Z every now and them to eliminate the slowness of Single data types. then using dim xxx as Single or Double but that is about it.

If you want to be able to check pasted text... you need to use this code and tweak it a little bit to work in the Text1_Change method. (If you are interested in this method and are not not sure what I am talking about... request a post below for an example)

I hope this answered most of the questinons so far... if there are any others feel free to post.
-Josh Sometimes... the BASIC things in life are the best...
cheers.gif

or at least the most fun ;-)
-Josh Stribling
 
>VB does not require you too... it does it for you

No, is doesn't. This is a false assumption. VB puts undeclared varables into variants, and then guesses what it is you want at any given time. It gets those guesses wrong plenty of the time, and can lead to difficult to track down bugs.

Try the following (very simple) illustration:

Private Sub Command1_Click()
Dim a As String
Dim b As Long
Dim c As Integer
' Don't bother with d


a = &quot;12345&quot;
b = 12345
c = 12345
d = 12345

Print Len(a)
Print Len(b)
Print Len(c)

' Will result below match that for a, b, or c?
Print Len(d)
End Sub
 
You are condidered un-professional if you do not use Option Explicit in Visual Basic. A misspelled variable becomes a new variable. On the Fly definition? You can put a Dim anywrhere in your procedure and initialize it.
Dim Temp as integer
Temp = 10

Phew! Worked-up a sweat on that one.

I tried your code. When I type
i like food.
it comes out
I Like food.

Also I can not highlight the text and press backspace to get am empty textbox.

Needs more work. TRy again. Forms/Controls Resizing/Tabbing Control
Compare Code (Text)
Generate Sort Class in VB or VBScript
 
However...
If you have been doing this stuff for longer than you can remember (or in other words half your life) you tend not to make mistakes like such and it REALLY doesn't matter...
Like I said... IF I NEED TO DIM A VARIABLE THEN I DO... wtf does it really matter anyways... the code works, it's proven, if YOU want to declare the variables... throw option explicit at the top of the program, dim the variables that throw an error (they're NOT that hard to figure out) and go on with your life... If you like the code... USE it, If you Don't then DON'T. In the real world I get paid to do this... stuff, so don't tell me what is professional and what's not, posting on this site is more or less just for fun, and maybe someone might be able to use something that I post that they could not figure out otherwise... Programing, for me is a 9 to 5 AND a hobby because I actually like problem solving... BUT... If it Ain't broke then don't fix it... So like I said... If you don't like it don't use it (PERIOD).

Now... Thank you JohnYingling for actually giving me a bug report...
here is the corrected code (which had NOTHING to do with Variants) the corrected code is in red and &quot;I Like food.&quot; is now &quot;I like food.&quot; and you can hightlight and press backspace or delete or what ever... and Just to make everyone happy and to stop all the pointless coversation on Option Explicit... I even included that (I had to define a whole 5 variables including the one I just added [SL].)

Code:
Option Explicit
Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
Code:
Dim SP As Integer, SL As Integer, Cap As String, I As Integer, TC As String
Code:
SP = Text1.SelStart
Code:
: SL = Text1.SelLength
Code:
Cap = UCase(Chr(KeyAscii))
If Cap = &quot;.&quot; Or Cap = &quot;!&quot; Or Cap = &quot;;&quot; Then
  For I = SP
Code:
+ SL
Code:
 + 1 To Len(Text1)
    TC = Mid(Text1, I, 1)
    If TC <> &quot; &quot; And TC <> Chr(8) Then
      Text1.SelStart = I - 1: Text1.SelLength = 1
      Text1.SelText = UCase(Text1.SelText)
      Exit For
    End If
  Next
Else
  If SP = 0 Then
    KeyAscii = Asc(Cap)
  Else
    If Mid(Text1, SP, 1) = &quot; &quot; Or Mid(Text1, SP, 1) = Chr(9) Then
      For I = SP To 1 Step -1
        TC = Mid(Text1, I, 1)
        If TC = &quot;.&quot; Or TC = &quot;!&quot; Or TC = &quot;;&quot; Then
          KeyAscii = Asc(Cap)
        Else
          If TC <> &quot; &quot; And TC <> Chr(9) _
          And TC <> Chr(13) And TC <> Chr(10) Then Exit For
        End If
      Next
      If I <
Code:
1
Code:
 Then KeyAscii = Asc(Cap)
    End If
  End If
End If
Text1.SelStart = SP
Code:
: Text1.SelLength = SL
Code:
End Sub

but as far as option explicit goes... I still ONLY use it for a debug tool... which all in all is what it IS for in the first place... (whether it is before or after you have a bug in your program)... for smaller programs... If you can't keep track of a small handfull of variables... do you really need to be programming (given the exception of a new programmer) like the following example...

Option Explicit
Function DumbLoop(N as integer) as String
Dim I as integer, Temp as String
For I = 0 to N
Temp = Temp + Trim(Str(I))
Next
DumbLoop = Temp
End Function

Half the Procedure is declarations...
Yet...

Function DumbLoop(N)
For I = 0 to N
Temp = Temp + Trim(Str(I))
Next
DumbLoop = Temp
End Function

...all in all does the same thing...
As you can see I is just a counter... and Temp is a temporary string to store the return data for the function...

Which brings me to my point... Option Explicit is as the name suggest... an option, which can be useful from time to time for new programers, Very Large Programs (Which if done right would not be in large sections), and otherwise lazy programers who do not want to keep track of a few variants in their head's...
My appologies if I have offened anyone with this statement, but... if the shoe fits... Wear It.

So... as a professional... I would consider it to be un-professional to use Option Explicit on a regular basis. If &quot;being professional&quot; has anything to do with having faith in the quality of your work.

Not that it is nessisarily a bad thing... but never the less far for something to base professionalism on.

I hope this is the end of the Option Explicit chat... I believe this has gotten far enough out of hand... Back to the point of this post... This is a tip... In other words something you might find useful... if you find a bug... By All Means... Please report it... thats what bug reports are for. So once Again and for future post... Thank you to anyone posting a change suggestion, idea for improvement, or a bug report... And please continue to do so... Other wise... Start a new thread or leave your comments at home.
Thank You,
happy coding;-)
-Josh Sometimes... the BASIC things in life are the best...
cheers.gif

or at least the most fun ;-)
-Josh Stribling
 
>So... as a professional... I would consider it to be un-professional to use Option Explicit on a [/i]regular basis[/i]

I think you may find that opinion is divided on this...

One of the points of these forums is to &quot;foster dialogue among professionals&quot; and, in the spirit of that, we tend to query each other's approaches and assumptions on occassion and provide alternative points of view. That's healthy. Getting upset when those points of view happen to be at odds with ones own is less so.

 
Being a Tip does not make it untouchable by criticism. We often point out to other programmers better or alternative means for their suggestions. The use of Option Explicit was an explicit suggestion as an improvement. You disagree strongly. Fine, but your rejection of the suggestion does not demote it to mere carping. &quot;Pride goeth before the fall&quot;... and typeless data has fallen way out of favor, in favor of strongly type data. But good luck in VB.Net with all those Variants becoming reference types instead of value types. Forms/Controls Resizing/Tabbing Control
Compare Code (Text)
Generate Sort Class in VB or VBScript
 
First off...
Is every programmer not different...
Thus, having different skills, styles, preferences, strong points, weak points, and opinions.

To get one point clear... I did not make my first quote being ..
&quot;So... as a professional... I would consider it to be un-professional to use Option Explicit on a regular basis. If &quot;being professional&quot; has anything to do with having faith in the quality of your work.&quot;
That was MY opinion to the quote made earlier in the thread...
&quot;You are condidered un-professional if you do not use Option Explicit in Visual Basic.&quot;
Which was someone elses opinion... That I do not nessisarily agree with. Not to say either opinion is wrong... they are both opinions. I don't recall a burning stack of 5.25&quot; floppies saying thou shalt use Option Explicit... In other words there is No Fact leading to prove either opinion right or wrong...
So I do agree with the above quote &quot;I think you may find that opinion is divided on this...&quot;
I'm sure there are plenty of people that live and breathe using Option Explicit and the rules that go along with the use of the option... I for one don't, and I personaly know plenty of others that also do not use it, as well as ones that do... Both of which, I consider to be &quot;Professionals&quot;. Now you can cut and paste anything you like to twist what I say into whatever you want to hear... But that does not mean that is what I meant when I said it... and you can take that however you like.

Once again, Like I said a few lines up...
Every programmer is different and has different styles and opinions.
My personal style is to use Option Explicit Only as a last resort, solely for debuging purposes...
I have been using the &quot;Basic&quot; language since it was Basic... Basica... GWBasic... QBasic/QuickBasic... on up through VisualBasic 5 & 6 and into VBScript.
I, Over the past 12 years (as many other progreammers have also done) have used a pretty good number of other programming languages. Including C/C++ (original, gnu, and extra crispy (VC++)), Pascal (MicroSoft, and Borland), Java and J++, Assembly from DEBUG all the way up through TASM on into VC++ inline Assembler. Data base query languages such as SQL and MQL (which is a specific Query Language for Matrix One), tcl/tk, etc... And plenty of other online languages such as Perl, php, asp, html, jscript, xml...

As most programmers do, I have developed my own style over the years with different experiences, and senarios at hand.

As far as critisism goes... yes there are times where it is good and in that time there are good and bad ways to express that opinion... Attacking one's style or preference in my opinion is bad form. Especially if it comes to stereo-typing on whether or not one is a professional because they have a different style of coding from your own.

this is an interesting article even though it is on information security...
...some points still hit close to home on every platform.

For example the part about...
&quot;There's something about being handy with a computer that tends to go to your head&quot;
&quot;The power of being able to manipulate all those bits makes you think you're invincible&quot;
&quot;The phenomenon of &quot;coder hubris&quot; takes many forms. Some attempt to create things before they've acquired the necessary expertise. Others try to reinvent the wheel rather than learning from the mistakes of the past.&quot;


Now, tell me this...
Is this not the reason for forumns?
With the reason being to share ideas and bad (or good) experiences with others in hopes that one day you might save yourself the embarassment of spending months trying to reinvent the wheel, as millions of others have done before.

With these things in mind... remember that I was not trying to attack anyone with the quotes that have been pulled from my posts. Those were my opinions to the attacks made toward my posts in the previous post.

And Note that when I said Thank You I was not being sarcastic... That was an overlooked error on my part that sprung off of the last change when I started munipulating the Cursor Position And restoring it without restoring the Selected text length... That, in my opinion, is what these forumns are for in the first place... otherwise that, most likely, would have gone over-looked.

Like I said before, and I'll say it again... If you have something That Relates To This Subject whether it is a question or suggestion... feel free to post...
After all... 99% of us are coders [pc3] here... the other percent need to consider a career in politics.[soapbox]
(Advice: Leave the mud-slinging to the ones [peace] who get paid to do it.)
...and remember to judge not, unless you yourself be judged.[hammer]

So... Once again happy coding, and have a nice day.:) Sometimes... the BASIC things in life are the best...
cheers.gif

or at least the most fun ;-)
-Josh Stribling
 
If you'd like to point out exactly where a cut and paste has twisted your words to a different meaning...

And a bug report: inserting a fullstop into the middle of a word incorrectly capitalises the letter following the inserted fullstop. Which means that if I type &quot;eg&quot; and realise that I really meant 'e.g.' I get 'e.G.'

And an exercise: most of the people who use declarations and Option Explicit in VB can usually make a solid case, with examples, of why it is a good idea. Very few people who use neither can make a solid case supporting their choice not to do so - apart from personal preference. Perhaps you could give us a couple of reasons why non-declaration is a good idea.
 

>Is every programmer not different

Therefore we need some standards - when we share/review code.

If you work on your own and no one else ever sees/uses your code, then I guess you can develop your own standards, completely, until your heart's happy, and what ever messes you get yourself into is your own worry, and, what ever advantages come out of your self developed standards are to your own advantages.

But, are we alone in the world?

We are not. Therefore, as soon as you start sharing code, especially if both parties have a common goal with that code, and/or are working on the same team, you need to conform to some common standards....otherwise the amount of errors, (not to mention the amount of wasted time), that could, and probably will arise from not doing so may be overwhelming.

Using 'Option Explicit' is a common standard amongst VB 5 & 6 programmers.

And, while not all programers are the same, or have the same opinions, not all programers have the same amount of progamming experience/insight/logic wisdom.

Imangine the amount of lost time and $$$ with-out these standards, trying to figure out as a professional what is being done, by another professional? We have to take a step backwards.

Try tracing code someone wrote and finding the error because that programer mis-typed a variable name.

What a waste of time amongst professionals, and an embarrasment because we are having to spend additional time finding an answer to a problem caused by some low level basic programming error - there are already enough of those problems around.

But in the case of this, variable name mis-types, it could have easily been prevented!

And don't let anyone tell say that they never mis-type.


[/b][/i][/u]*******************************************************
General remarks:
If this post contains any suggestions for the use or distribution of code, components or files of any sort, it is still your responsibility to assure that you have the proper license and distribution rights to do so!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top