Solved

VB6 - Links and others

Posted on 2004-09-28
32
673 Views
Last Modified: 2008-03-10
How do I create a clickable link in Visual Basic 6?  I want to add it to a drop down menu if possible (the link that is).

My other question is, how (if possible) to allow the user to highlight some word in the textbox and do a search for it on Google?

Thanks.
0
Comment
Question by:greyknight17
  • 22
  • 10
32 Comments
 
LVL 16

Accepted Solution

by:
jimbobmcgee earned 500 total points
ID: 12170927
Quick and dirty answer to question two is

(in General Declarations)
Private Declare Function ShellExecute Lib "shell32.dll" _
    Alias "ShellExecuteA" _
    (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile _
    As String, ByVal lpParameters As String, _
    ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Const SW_SHOWNORMAL = 1


(in a form with one textbox: TextBox1 and one button: CommandButton1)
Private Sub CommandButton1_Click()

    Dim strSearch       As String
    Dim strGoogle       As String
   
        strSearch = TextBox1.SelText
       
        strGoogle = "http://www.google.com/" & _
                    "search?hl=en&ie=UTF-8&q=%2B%22" & _
                    strSearch & _
                    "%22"                                                       'generate Google search URL
                   
        ShellExecute Application.hWnd, vbNullString, strGoogle, vbNullString, "C:\", SW_SHOWNORMAL
                                                                                    'Open Google search URL in IE
   

End Sub

That uses the current Google setup/search method, within IE...
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12170956
I guess, clickable link in a combobox would be similar, but you would adapt the code above to fit the SelectedItem of your list, in your list's Click event...
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12171023
Again, quick and dirty answer to question one:

(In General/Declarations of your form)
Private Declare Function ShellExecute Lib "shell32.dll" _
    Alias "ShellExecuteA" _
    (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile _
    As String, ByVal lpParameters As String, _
    ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Private Const SW_SHOWNORMAL = 1



(In a form with a combobox: ComboBox1)
Private Sub ComboBox1_Click()

    Dim strURL      As String
       
        strURL = ComboBox1.List(ComboBox1.ListIndex)
       
        ShellExecute Application.hWnd, vbNullString, strURL, vbNullString, "C:\", SW_SHOWNORMAL
       

End Sub
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12171035
Whoops: both codes are working in VBA, in Excel.  To make them work in VB6, you probably need to change

    Application.hWnd

to

    Me.hWnd

or something like that, to get it to work properly...
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12171069
And, I forgot, you will need to populate your combobox, in the second code example, with fully qualified URLs

I had

    ComboBox1.AddItem "http://www.google.com"
    ComboBox1.AddItem "http://www.bbc.co.uk"
    ComboBox1.AddItem "http://www.experts-exchange.com"

in my Form1_Activate() sub.

(I told you they were quick and dirty!!)

:-)
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12171514
Thanks for the quick reply.  I will try this out (hopefully tonight) and tell you what happened tomorrow.

Do I need to declare or call anything here?  I'm no expert in VB but know things here and there.  I mean is that all I need for my program to work (no calls or anything else to add in the top declaration part)?

Thanks.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12171999
You'll need

    Private Declare Function ShellExecute Lib "shell32.dll" _
    Alias "ShellExecuteA" _
    (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile _
    As String, ByVal lpParameters As String, _
    ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

in your form declarations but, other than that, it should work fine...
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12179381
jimbobmcgee, I think it worked partially.  Not sure if I did something wrong, but for some of the code, I changed it a little (just from a couple of lines to one line).  Is the following correct:

strGoogle = "http://www.google.com/" & _
                    "search?hl=en&ie=UTF-8&q=%2B%22" & _
                    strSearch & _
                    "%22"    

All I did for that one is put them all in one line instead of the multiple lines.  Either way I tested it out and all Google came up with to search is:      +" "

I entered some text and not +" "

Should this be the url:

strGoogle = "http://www.google.com/search?hl=en&lr=&ie=UTF-8&q="

instead?  I tried it with that also and didn't work.  Do I add a & strSearch or + strSearch at the end?

The combo box won't work either.  I created the combo box and then put the code in it.  Then I put the AddItem lists into the form_activate sub.  I see the list and could have a drop down, but nothing happens when I click on it.

I followed all your directions and changed the Application to Me also.

I have other questions, but will ask them after this is resolved.

The point value will be increased to 300 points since I'm giving more trouble now (LOL).

Thanks.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12180831
If you put all of them into one line, you should remove the _'s; I expect you did that correctly.  

strSearch is in that line, between both %22's (%22 being the web-method for entering a ").  If your search came up with ' +" " ', then I expect that you did not select any text in your textbox first (strSearch = TextBox1.SelText only gives the selected text).  If you want all text in the textbox, you should use TextBox1.Text, instead of Textbox1.SelText.

Instead of using Me, or Application, perhaps you can use anothe window handle -- does Form1.hWnd work? -- it might be trying to use a handle to the combobox, or something like that...
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12181411
Bingo.  I selected and it worked.  The reason I didn't select it was because I wanted to have a right context menu to do the search (which wasn't implemented yet).  I changed it to .text instead also and worked perfectly.  Do I really need the +"mySearchTermHere" in quotes and the + in front?  Doesn't really matter since it works, but just curious.

For some the combo box will still not work.  Once I select say the Google link, it should open up IE right?  I just changed the combobox name for the code.  The combo box properties name is also changed.  Still doesn't work.  When you say form1.hwnd, I assume you mean the main form's name that I gave it.  I did that, didn't work either.

I want to add the other questions I had before.

1. Originally for the search, I want the user to be able to select the text and right click then click search on google or something.  Is this going to be a difficult task to do?  Hopefully it could be one of your " quick and dirty answers" (LOL).  Perhaps even search under more than one search engine?

2. Any code to make a label or any other objects hyperlinks?  I want the user to be able to click on a link to my homepage on the main program.

3. I have multiple files that I want to compare with the user entered textbox.  So this is another textbox I created.  Users will copy and paste information into this textbox.  I will have like 4 or 5 text (notepad) files that have some information in them.  If there are any matches I want it to be outputted to another file with certain text (let's say for our purposes if something is found in file1.txt that it will output the following text: The first file's text that matches are:....).  I want to compare this with all the txt files.  After that, if some user entries are still not found, I want it appended to the bottom.

I keep coming up with more and more questions.  I'm sure this is probably going to take more time, but if not, that would be great.  I like your quick and diry answers.  Keep shootin' them down.

I will increae another 100 points.

Thanks.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12184693
>> Do I really need the +"mySearchTermHere" in quotes and the + in front?

Google uses this +"..." function to search for an exact term; if you don't want exact searching, do a search in Google for something and see what happens to IE's address bar when it completes the search -- then copy the format into strGoogle...


>> right click then click search on google ... Perhaps even search under more than one search engine?

http://www.fawcette.com/archives/premier/mgznarch/vbpj/2000/02feb00/gs0200/gs0200.asp has some detailed information on context-sensitive menus -- it's not straight forward but, instead of the Google format I detailed, you would substitute the method used by other search engines and call the code in your menu click events: have a read of that link and then research the address bar output for other search engines...

(Hint: Altavista uses http://www.altavista.com/web/results?itag=wrx&q=%2B%22SEARCHSTRING%22&kgs=0&kls=1 so

   strAltaVista = "http://www.altavista.com/web/results?itag=wrx&q=%2B%22" & _
                       strSearchString & _
                       "%22&kgs=0&kls=1"

now call ShellExecute with strAltaVista as the property...


>> Any code to make a label or any other objects hyperlinks

Most controls have a click event -- use Label1_Click for a label, calling either Label1.Caption as the URL in ShellExecute, or another property, like Label1.Tag


>> If there are any matches I want it to be outputted

A case of open each file (best done with the File System Object) and reading the contents of the file:  Use Instr(1, strFileContents, strTextToFind) to determine if text is within a string:

   Function CheckFile(strTextToFind as String, strFileName as String) as Boolean
     
      Const ForReading = 1

      Dim objFSO, objFile
      Dim strBuffer as String
     
      Set objFSO = CreateObject("Scripting.FileSystemObject")
      Set objFile = objFSO.OpenTextFile(strFileName, ForReading)        'OPEN TEXT FILE TO SEARCH
     
      strBuffer = objFile.ReadAll               'READ ALL FILECONTENTS INTO BUFFER

      If InStr(1, strBuffer, strTextToFind) then             'IF strTextToFind IS IN strBuffer THEN
   
         CheckFile = True                        'RETURN TRUE

      Else                                                                'OTHERWISE
 
         CheckFile = False                       'RETURN FALSE

      End If

   End Function

Now you would call your search routine with
 
   blnFound = CheckFile("x:\mypath\myfile.txt", "find this text")

or
 
   If CheckFile("x:\mypath\myfile.txt", "find this text") = True then

      msgBox "Found text string"

   Else

      msgBox "Not found"

   End if

should do it, reasonably well...
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12189463
Thanks, the link will be bookmarked.  I will also try out the code you gave me tonight.

If you have time, I still have a couple more questions (I know, it's probably too much already - LOL - just excited that this is all working so smoothly now).  I will increase another 100 points.

1. How do I add a search feature to look for words in one of my textboxes?  I want to enable the user to look for some text in one of the textboxes.

2. How do I create a command button that will copy all the contents in a textbox?

3. I created a menu that has similar code to the Google search you gave me.  The problem is that some entries in my menu also have a submenu.  Both the entry itself and the submenu are links.  The problem is that when I click on the menu and just hover over the entry, it will automatically bring up IE.  This doesn't happen to the submenu.  How can I prevent it from auto launching IE until it's clicked on?

Hopefully that would be my last batch of questions for now.  You have helped me out a great deal here.  After this I might have to help out others also (need to get back some points - LOL).

Kevin.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12195977
Simple search feature (requires Form1, with textbox: Text1, button: Command1, Form2, with textbox: Text1, button: Command1 and button: Command2)

[Form1 code]
    Private Sub Command1_Click()       'CODE FOR SEARCH BUTTON
   
        Form2.Show             'SHOW THE SEARCH FORM
   
    End Sub
 
[Form2 code]
    Public iStart As Integer        'SHARED VARIABLE -- START POINT OF SEARCH
    Public sFind As String          'SHARED VARIABLE -- TEXT TO FIND
   
   
    Private Sub Command1_Click()         'CODE FOR FIND NEXT BUTTON
     
        sFind = Form2.Text1.Text           'SET TEXT TO FIND TO BE CONTENTS OF FORM2 TEXTBOX
       
        With Form1.Text1            'APPLY FOLLOWING PROPERTIES TO THE TEXTBOX ON FORM1 (SHORTHAND CODE)
       
            If InStr(iStart, .Text, sFind) = 0 Then         'IF FIND TEXT IS NOT IN TEXTBOX
           
                 MsgBox "Not Found"                'SHOW NOT FOUND MESSAGE
                 Unload Form2                    'UNLOAD FORM, WHICH WILL RESET THE START POINT NEXT TIME
             
            Else                                                         'IF FIND TEXT IS IN TEXTBOX
             
                .SelStart = InStr(iStart, .Text, sFind) - 1        
                .SelLength = Len(sFind)                             'SELECT THE FOUND TEXT
                .SetFocus
                 
            End If
           
            iStart = .SelStart + .SelLength                  'MOVE START POINT TO AFTER THE FOUND TEXT, FOR A 'FIND NEXT' FEATURE
             
        End With              'END SHORTHAND CODE
           
    End Sub
   
   
    Private Sub Command2_Click()              'CODE FOR CANCEL BUTTON
   
        Unload Form2            'UNLOAD SEARCH FORM
   
    End Sub
   
   
    Private Sub Form_Load()        'WHEN THE FORM LOADS
   
        sFind = ""          'RESET SEARCH STRING
        iStart = 1          'RESET START POINT
   
    End Sub
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12196012
2:  Where do you want to copy all text to?  The clipboard?

[In a form: Form1, with a textbox: Text1 and a button: Command1]
   Private Sub Command1_Click()

       Clipboard.Clear
       Clipboard.SetText (Text1.Text)           'COPY ENTIRE TEXTBOX

   End Sub

or

   Private Sub Command1_Click()

       Clipboard.Clear
       Clipboard.SetText (Text1.SelText)           'COPY SELECTED TEXT IN TEXTBOX

   End Sub
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12196038
3:

Are you using two menus?  Like two lists?  The problem with my quick solution at the top, is it fires as soon as the list is clicked on...
If you want a submenu system, make the first list populate the second list and fire the shellexecute in the click event of the second list.

If this isn't possible, perhaps use a TreeView contol, instead of a list.  Fire the shellexecute on the NodeClick event - then you can have menus, submenus, etc.

If not, what menu system are you using?

Right, now I'm going to sleep...!
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12199523
Hi again, for the menu, I created it with the Menu Editor.  It has a drop down with 4 other entries.  For these entries, I have included a link in them already.  I also included a submenu for each of those other 4 entries to other links (they are just mirror links - in case the main site is down).  The problem is that once I hover over any of these 4 main entries, they open IE immediately.  I want the user to click on it instead.  So to make a picture overview:

Links
...link1
......mirror for link1
...link2
......mirror for link2
....etc.

That's how I set up the link in the Menu Editor.

For the search, could I use another textbox within the same form?  I'll just hide the other one and have a button to go back if needed to the first textbox.

I just want the user to be able to copy the text so they can paste it somewhere later on.  Are the text/code in parentheses required here (Text1.Text)? 'Clipboard.SetText (Text1.Text)'

For the other question regarding comparing files, I was a little confused on it when I took another look yesterday.  Does the code search for the text that the user entered in a textbox?  I just want to compare the textbox (user entered data) line by line with my other 4 txt files.

Thanks.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12200208
The search feature I posted will probably work within the same form but I created the little 'search form' to make it look as much like regular 'Find Next' functions as I could.

If you have

    ...mnuA
    .......mnuA1
    .......mnuA2
    ...mnuB
    .......mnuB1
    .......mnuB2

then mnuA_Click might be a valid event, along with mnuA1_Click.  If not, you might want to insert another menu item at the top of each submenu for the primary site.

Clipboard.SetText(Text1.Text)  will copy all the text in Text1 to the clipboard.

As for the 'Find in file' function,

>>    If CheckFile("x:\mypath\myfile.txt", "find this text") = True then

            msgBox "Found text string"

        Else

            msgBox "Not found"

        End if

that routine, to call the CheckFile function, will tell you if "find this text" exists in "x:\mypath\myfile.txt" (it returns True (-1) if it does).  If you fiddle around a bit, you can use it to check your text box, across four files.  Simply put:

      Dim strFilesToCheck(1 to 4) as string
      Dim i as integer
      Dim blnFound as boolean
 
         strFilesToCheck(1) = "x:\mypath\checkfile1.txt"
         strFilesToCheck(2) = "x:\mypath\checkfile1.txt"
         strFilesToCheck(3) = "x:\mypath\checkfile1.txt"
         strFilesToCheck(4) = "x:\mypath\checkfile1.txt"

         blnFound = false
 
         For i = 1 to 4

             If Checkfile(strFilesToCheck(i), Text1.Text) = True then
                MsgBox "Text found in file: " & strFilesToCheck(i)
                blnFound = true
             End if

         Next i

         If not blnFound then MsgBox "Not found."

will give you up to four results depending if the text in Text1 is found, or a simple 'notr found' message, if not.

HTH
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12200226
Sorry, the section

         strFilesToCheck(1) = "x:\mypath\checkfile1.txt"
         strFilesToCheck(2) = "x:\mypath\checkfile1.txt"
         strFilesToCheck(3) = "x:\mypath\checkfile1.txt"
         strFilesToCheck(4) = "x:\mypath\checkfile1.txt"

should contain different filenames, otherwise you'll search the same file four times, e.g.:

         strFilesToCheck(1) = "x:\mypath\checkfile1.txt"
         strFilesToCheck(2) = "x:\mypath\checkfile2.txt"
         strFilesToCheck(3) = "x:\mypath\checkfile3.txt"
         strFilesToCheck(4) = "x:\mypath\checkfile4.txt"

Regards,
J
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12201933
You're a genius!  I actually understood that part too.  I have to say, I've been to a lot of forums and got answers before, but no one explains it better than you do.  

I'm not sure if I should end this and give you the points yet.  I will try this out tonight and see what happens.  If anything, I'll keep adding more points to it afterwards instead of creating another topic.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12216884
I can't guarantee its the best way to do it, but simple click events are exactly that -- simple.  I'm sure there are many different (and better) ways to achieve this but I hope you can adapt these ideas to find your own personal favourite method...
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12217272
I tried this out and didn't have time to post back here.  It seems I'm having some problems with it.  Here's another batch of questions:

1. Any way to open a URL in the same IE window?

2.For the search feature (searching in another textbox in the program), I'm not sure exactly how it works.  It's the reply Dated: 09/30/2004 05:18PM PDT for your reference.  Is it only matching the exact text of each line?  For example, if I put 'testing 1 2 3', the word 'testing' itself is not found.  I want it to be included (even if only partial of the word is found).  

search feature cont'd - It seems like I have to enter text into the first form and then click on the command button.  Then I have to click on the command button on the second form also to do a search.  Is there a way to click on the bottom on Form one and just show the textbox with the matching text selected?

3. Is this code correct for the 'Find in File' code:
--------------
   Function CheckFile(strTextToFind As String, strFileName As String) As Boolean
     
      Const ForReading = 1

      Dim objFSO, objFile
      Dim strBuffer As String
     
      Set objFSO = CreateObject("Scripting.FileSystemObject")
      Set objFile = objFSO.OpenTextFile(strFileName, ForReading)        'OPEN TEXT FILE TO SEARCH
     
      strBuffer = objFile.ReadAll               'READ ALL FILECONTENTS INTO BUFFER

      If InStr(1, strBuffer, strTextToFind) Then             'IF strTextToFind IS IN strBuffer THEN
   
         CheckFile = True                        'RETURN TRUE

      Else                                                                'OTHERWISE
 
         CheckFile = False                       'RETURN FALSE

      End If

   End Function


Private Sub Command1_Click()

     Dim strFilesToCheck(1 To 4) As String
      Dim i As Integer
      Dim blnFound As Boolean
 
         strFilesToCheck(1) = "c:\file.txt"

         blnFound = False
 
         For i = 1 To 4

             If CheckFile(strFilesToCheck(i), Text1.Text) = True Then
                MsgBox "Text found in file: " & strFilesToCheck(i)
                blnFound = True
             End If

         Next i

         If Not blnFound Then MsgBox "Not found."

End Sub
-------------------
I put that all in the same form as it's listed above.  I get a runtime error 53 when I click on the command button.  Just couldn't get this to work.  Do I need to add anything in the forum itself?  I just put in the code and no objects in the physical (gui) form.

Thanks.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12220377
1.  Try creating an object that is an instance of Internet Explorer, instead of ShellExecute-ing -- I think it is done
     with set objMyIE = CreateObject("Internet.Explorer"), but you'll have to look it up, to be sure.
     When you have you IE object, you can use its properties to navigate -- something like:
     
             set objMyIE = CreateObject("Internet.Explorer")
                  objMyIE.NavigateTo strURL

     I'll get back to you with the exact format, when I have time...

2.  My search routine will find all instances of a string within the text box.  If your text box says:
   
             Hello, my name is Joe and I am learning Visual Basic

     searching for 'is' will find and highlight the first:

             Hello, my name is Joe and I am learning Visual Basic
                                    ^
     clicking the button again will find and highlight:
 
             Hello, my name is Joe and I am learning Visual Basic
                                                                         ^
     It is case-sensitive but not whole-word-sensitive, so searching for 'joe', will not find 'Joe'.  If you want to avoid
     case-sensitivity, convert all strings and text input to upper case (in memory, only), with Ucase(strString).

3.  Error code 53 is a file not found error.  When you click the button, it is trying to open "c:\file.txt", which does
     not exist.  Either:

      (a)   Change strFilesToCheck(1) = "c:\file.txt" to a file that does exist
      (b)   If there is less than 4 files, change the size of the array and the number of times it loops.

                 Dim strFilesToCheck(1 To 4) As String  -> should be (1 To 2) if there are two files
                 For i = 1 To 4  -> should be For i = 1 to 2, if there are two files

             otherwise, VB might be trying to open a file with no name...

HTH
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12225307
OK, the method for opening a page in an existing Internet Explorer (or creating one if it doesn't exist) is:

    In Project -> References menu item, add a reference to Microsoft Internet Controls/Objects.

    [In Global/Declarations, of a module]
        Global objMyIE                                'DEFINE objMyIE AS AVAILABLE TO ALL PROCEDURES

    [In Link-handling routine]
        If objMyIE = Nothing Then Set objMyIE = CreateObject("InternetExplorer.Application")
                                                             'CREATE INTERNET EXPLORER IF IT DOES NOT EXIST

        objMyIE.Visible = True                     'SHOW INTERNET EXPLORER WINDOW
        objMyIE.Navigate2 strURL                 'GO TO THE ADDRESS STORED IN strURL

        Do While objMyIE.Busy                     'LET INTERNET EXPLORER DO WHAT IT HAS TO DO
             DoEvents
        Loop

    [In Internet Explorer closing routine]
        If objMyIE <> Nothing Then             'IF INTERNET EXPLORER OBJECT EXISTS...
           objMyIE.Quit                                    'CLOSE INTERNET EXPLORER
           Set objMyIE = Nothing                      'CLEAR THE OBJECT THAT WAS INTERNET EXPLORER
        End If

Now, all references to objMyIE will apply to the one Internet Explorer window.

Read http://visualbasic.about.com/library/blnewieinstance.htm and http://www.microsoft.com/resources/documentation/windows/2000/server/scriptguide/en-us/sas_ent_qpyo.mspx for more information on using the Internet Explorer object.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12227661
>> For example, if I put 'testing 1 2 3', the word 'testing' itself is not found.  I want it to be included (even if only partial of the word is found).

No easy solution to that.  You'll need to split the string up into an array and search for each individual array element.

Let's see.  The following will take a search term, split it into words, search for each word, populate a list of results and cycle through them.  IT ONLY SEPARATES WORDS WITH SPACES, PUNCTUATION IS SEARCHED FOR LITERALLY.  It should work in VB6, although I wrote it in VBA.  Again, it works better with two forms, as the loading/unloading of the search form resets some variables, but you should be able to convert to one form.  Here goes:

  [UserForm1 - contains a textbox: TextBox1 and a button: CommandButton1]
    Private Sub CommandButton1_Click()
   
        UserForm2.Show False                'SHOW FORM NON-MODALLY
   
    End Sub


  [UserForm2 - contains a textbox: TextBox1, a 'Find Next' button: CommandButton1 and a 'Cancel'...]
  [...button: CommandButton2]
    Private SortedResults()
    Private ResultsPointer As Long
    Private GotResults As Boolean      'DECLARE VARIABLES FOR USE IN ALL PROCEDURES IN THE FORM
   
   
    Private Sub GetResults()
   
        Dim SearchWords
        Dim TotalResults As Long
       
        SearchWords = Split(UCase(UserForm2.TextBox1.Text), " ")
       
        'COUNT EACH INSTANCE OF SEARCH TERMS '''''''''''''''''''''''''''''''''''
        ReDim ResultsPerWord(LBound(SearchWords) To UBound(SearchWords)) As Long
       
        For w = LBound(SearchWords) To UBound(SearchWords)
       
            StartPoint = 1
            Do Until InStr(StartPoint, UCase(UserForm1.TextBox1.Text), SearchWords(w)) = 0 _
                                                                    Or StartPoint = 0
                                                                   
                ResultsPerWord(w) = ResultsPerWord(w) + 1
                StartPoint = InStr(StartPoint, UCase(UserForm1.TextBox1.Text), SearchWords(w)) + 1
           
            Loop
           
            TotalResults = TotalResults + ResultsPerWord(w)     'INCREMENT TOTAL RESULTS COUNT
           
        Next w
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
       
        If TotalResults < 1 Then
            GotResults = False
            Exit Sub
        End If
       
        'POPULATE ARRAY OF RESULTS''''''''''''''''''''''''''''''''''''''''''''''
        ReDim unsortedresults(1 To TotalResults, 0 To 1)
       
        c = 1
       
        For w = LBound(SearchWords) To UBound(SearchWords)
            StartPoint = 1
           
            Do Until InStr(StartPoint, UCase(UserForm1.TextBox1.Text), SearchWords(w)) = 0 _
                                                                    Or StartPoint = 0
                                                                   
                unsortedresults(c, 0) = _
                        InStr(StartPoint, UCase(UserForm1.TextBox1.Text), SearchWords(w))
               
                unsortedresults(c, 1) = Len(SearchWords(w))
               
                c = c + 1
               
                StartPoint = InStr(StartPoint, UCase(UserForm1.TextBox1.Text), SearchWords(w)) + 1
           
            Loop
        Next w
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
       
        'SORT RESULTS ARRAY INTO ORDER THEY APPEAR IN TEXTBOX1.TEXT'''''''''''''
       
        ReDim SortedResults(1 To TotalResults, 0 To 1)
                                                    'CREATE ARRAY TO STORE SORTED RESULTS
       
        ReDim SortCounts(1 To Len(UserForm1.TextBox1.Text) + 1)
                                                    'CREATE ARRAY TO COUNT EACH INSTANCE OF A
                                                    'PARTICULAR RESULT
   
        For i = 1 To TotalResults
            SortCounts(unsortedresults(i, 0)) = SortCounts(unsortedresults(i, 0)) + 1
                                                    'COUNT THE INSTANCES OF EACH RESULT
        Next i
   
        SortNextOffset = 1
        For i = 1 To Len(UserForm1.TextBox1.Text)
            SortThisCount = SortCounts(i)
            SortCounts(i) = SortNextOffset
            SortNextOffset = SortNextOffset + SortThisCount
        Next i                                      'ORDER EACH RESULT DEPENDANT ON WHERE
                                                      'IN UserForm1.TextBox1.Text THEY APPEAR
   
        For i = 1 To TotalResults
            SortedResults(SortCounts(unsortedresults(i, 0)), 0) = unsortedresults(i, 0)
            SortedResults(SortCounts(unsortedresults(i, 0)), 1) = unsortedresults(i, 1)
            SortCounts(unsortedresults(i, 0)) = SortCounts(unsortedresults(i, 0)) + 1
        Next i                                      'WRITE THE SORTED ARRAY
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
       
        GotResults = True
        ResultsPointer = 1           'SET FOUND FLAG AND ARRAY ELEMENT INDICATOR
       
    End Sub
   
   
    Private Sub CommandButton1_Click()
   
        If GotResults = False Then Call GetResults
                                    'START SEARCH IF NOT ALREADY DONE
       
        If GotResults = False Then
                                    'IF NOT FOUND THEN...
       
            MsgBox "Not found"
            Exit Sub
           
        End If
       
        If ResultsPointer > UBound(SortedResults(), 1) Then
       
            ResultsPointer = UBound(SortedResults(), 1)
           
            If MsgBox("Last instance found.  Search again?", vbYesNo) = vbYes Then
                ResultsPointer = LBound(SortedResults(), 1)
            Else
                GotResults = False
                Exit Sub
            End If
           
        End If     'LOOP THE CYCLE THROUGH RESULTS IF USER SPECIFIES
   
        UserForm1.TextBox1.SetFocus
        UserForm1.TextBox1.SelStart = SortedResults(ResultsPointer, 0) - 1
        UserForm1.TextBox1.SelLength = SortedResults(ResultsPointer, 1)
                                         'SELECT THE NEXT INSTANCE OF A FOUND SEARCH WORD
       
        ResultsPointer = ResultsPointer + 1
                                         'INCREMENT THE ARRAY ELEMENT COUNTER TO GET NEXT SEARCH TERM
           
    End Sub
   
    Private Sub CommandButton2_Click()
   
        GotResults = False
        Unload UserForm2      'CLEAR ALL RESULTS ON 'CANCEL'
   
    End Sub
   
    Private Sub TextBox1_Change()
   
        GotResults = False     'CLEAR ALL RESULTS IF SEARCH TERM CHANGES
   
    End Sub

Please don't ask for explanations of this -- I made it up, on the fly and probably won't remember!!

HTH

J.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12227706
BTW, the code posted directly above is not case-sensitive.  It converts (in memory) the text to find and text to search in, to upper case, so

     hello = Hello = HELLO = HeLlo = hELLo ...

I used some Lorem Ipsum (http://www.lipsum.com) in UserForm1.TextBox1 and did a search for 'lorem dolor ip'.  It found all instances, in order.

I'm proud of that bit of code...!!

J
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12228636
More code to add, whoopee...

Regarding the Error code 53 file not, i changed the loop to go from 1 to 2 and even 1 to 1 in the FilesToCheck and the for loop.  I also created a test file in c:\ and it still gives me the error.  I don't need to create any object in the GUI form do I?

I will try out the other code you gave me tonight.  Do you know if I can open up the google search in another browser like (Firefox)?  I see all those objMyIE are most likely for IE.

Thanks.
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12228965
I want to add something else.  Is there a way to add many lines of text to a textbox without having the user to click on it?  I know the default is Text1 in the Text Properties.  I have added many lines or text into the Text Property but some of them don't come out right.  Let's just say I want to print out:

The quick brown fox jumps over the lazy dog.

Instead it might come out like:

The quick brown fox jumps
over the
lazy dog.

I want them all in one line if they fit.  If not, they should start off the next line.  I did a copy and paste job from Notepad to VB6 to make sure that there is no other formatting in there.

Is there a way to make the text show up automatically using VB code?  I know how to use the Click in the code, but that will only show up if the user clicks on a button or something.

Another question, how do I make it so that my program will always show up in the taskbar?  I was having some problems the other day in XP and had to end explorer.exe only to find that I can't see my program anymore.  I had to end the process for my program also and then run it again.

Thanks.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12235996
>> Regarding the Error code 53 file not...

OK, time for some debugging;  set a breakpoint (press F9) at

    Const ForReading = 1

When the program breaks, step through with F8, until you get to your error.  Error 53 is, without doubt, a File Not Found error.  When you reach it, choose 'Debug' (in the error message box), open the Immediate window (View -> Immediate Window) and type:

   Print strFileName

This will show you the file you are trying to open.  It must match the full path and filename of the file you want to open.  If it doesn't; there's your problem.


>> Do you know if I can open up the google search in another browser like (Firefox)?

If FireFox has an object library you can reference (Project -> References) in VB6, you can create its objects, instead of IE's (you're on your own for that, though).  Otherwise ShellExecute-ing a URL will open that URL in the system's default browser.  If you want to code it to open in the same window each time, your going to have to deal with window handles, Windows Messages, etc to 'talk' to an existing browser window (again, you're on your own).  If you create and use an IE object, you can have direct control over it, far more simply...


>> ...The quick brown fox jumps over the lazy dog...

Not too sure what your asking here; if you want to add text to a multiline textbox you use

      Text1.Text = Text1.Text & strTextToAdd

If you want a new line use

      Text1.Text = Text1.Text & vbCrLf

If you don't want text to wrap, you can set Text1.WordWrap = False
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12236023
Ahh, I reread your question

>> ...The quick brown fox jumps over the lazy dog...

Try the following:

    [UserForm1 - Contains two identical textboxes: txtAttempt, txtCommit and a button: CommandButton1]
        Private Sub btnAddText_Click()
       
            Dim strText     As String
            Dim lngLinesA   As Long
            Dim lngLinesC   As Long
           
            strText = "Lorem ipsum"
           
            txtAttempt.Text = txtAttempt.Text & strText
                                    'ADD TEXT TO ATTEMPT BOX
           
            txtAttempt.SetFocus
                lngLinesA = txtAttempt.LineCount
                                    'GET NEW NUMBER OF LINES IN ATTEMPT BOX
           
            txtCommit.SetFocus
                lngLinesC = txtCommit.LineCount
                                    'GET CURRENT NUMBER OF LINES IN COMMIT BOX
           
           
            If lngLinesA > lngLinesC Then
                                    'IF MORE LINES IN ATTEMPT BOX THEN TEXT
                                    'DOES NOT FIT ON ONE LINE
           
                txtCommit.Text = txtCommit.Text & vbCrLf & strText
                                    'WRITE TEXT ON NEW LINE IN COMMIT BOX
               
            Else
           
                txtCommit.Text = txtCommit.Text & strText
                                    'WRITE TEXT ON CURRENT LINE IN COMMIT BOX
               
            End If
           
       
        End Sub
       
        Private Sub txtCommit_Change()
       
            txtAttempt.Text = txtCommit.Text
                                    'UPDATE THE CONTENTS OF ATTEMPT TO MATCH
                                    'COMMIT, MAKING LINE COUNTS EQUAL
       
        End Sub

While debugging, to check it works, show both textboxes side-by-side.  For a release version, hide txtAttempt behind txtCommit.  txtAttempt.Visible _must_ be true because you have to set the focus to it to get the number of lines (and you can't set the focus to an invisible object).

HTH

J
0
 
LVL 15

Author Comment

by:greyknight17
ID: 12262435
Too complicated (LOL).  I will take another look, but don't want to bog you down anymore.  I will get a VB Windows API.

Points will be awarded to you.  Just one last question, I created a menu and have 3 entries (submenus right below it).  I gave those 3 entries each a shortcut key.  Then I made only the top/root menu inivisible (visible is unchecked).  I hit the shortcut keys when I run the program and nothing happens.  Just to double check that it works, I made the root menu visible and hit the shortcut keys.  It worked.  Any reason why it won't work if it's invisible?  Any way around it?

I will award the points to you now.

Thanks so much for your time.  If you have more time, could you answer the last question also?

Kevin.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12285202
I think, when the menu is invisible, it is also not enabled.  I know you cannot do certain things to things that aren't visible (like setting the focus).  I imagine shortcut key monitoring is included.  

Alternatively, you could set your Form's 'KeyView' property to True, and use the form's KeyDown, or KeyPress events to handle all the different possible shortcuts.  Then you wouldn't need the invisible menu...

HTH

Thanks for the points

J.
0
 
LVL 16

Expert Comment

by:jimbobmcgee
ID: 12285217
>> Too complicated (LOL).

The word-wrap thing?  That's probably the second-easiest thing here!!  Now, the word searcher, _that_ was complicated.  Even I can't remember how it works!!

J
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

I’ve seen a number of people looking for examples of how to access web services from VB6.  I’ve been using a test harness I built in VB6 (using many resources I found online) that I use for small projects to work out how to communicate with web serv…
Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now