K & K Consulting    K & K Consulting

K&K Home VB Guru Home Search VB Site VB Code VB Tips VB Tutorials VB Questions

K&K Home


Answered Questions For June 2000


Pass a String Between the Forms

From:  Harold Waters
Date:  June 25,2000

I have an application that has three forms. What is the best way to pass a string between the forms?

The Guru's Response:

There are a few ways to do this, depending on exactly what you want to do.  If you want to be able to set, retrieve and use the string, on all the forms, the easiest way to do it, is to use a Global Var.  Create a BAS module in your project, under the Option Explicit tag, add the following line:

Public MyString As String

If you want to "pass" a string from other forms to one specific form, you can do it one of two ways, the first one is the easiest, just do the same as the last example, but paste it into the form, instead of a BAS file.  The other way is a bit more code, but is more OOP centered.  Paste the following code onto your form:

Option Explicit
Private mvarMyString As String

Public Property Let MyString(ByVal Data As String)
     mvarMyString = Data
End Property

Public Property Get MyString() As String
     MyString = mvardata
End Property

Either way you do it, you set MyString the same way:  MyForm.MyString = "This is a test".  For the first example, you just code: MyString = "This is a test"

MSFlexGrid Editing

From:  HercZ
Date:  June 22,2000

Hi guru, 

I have a msflexgrid control. I want the user to input some data. But I when I click the cell, it won't put itself in edit mode. How do u edit these cells? 



The Guru's Response:

Hey Herc, I have no idea why Microsoft has not added direct editing to the FlexGrid Control; I guess it has been designed for read only, databinding.  Anyway, I have posted the standard work around that I always use, it is a bit long, but it works great.

MSFlexGrid does not have a built-in cell editing capability, but it provides the hooks to make it easy for you to add that capability programmatically. The advantage of this approach is that you can tailor editing behavior to your taste. The basic technique involves smoke and mirrors: the editing occurs not in MSFlexGrid at all, but in a standard Textbox control that is positioned precisely over the cell being edited.

In this example, we will give the user two ways to get into the edit mode, either by double-clicking on a cell, or by simply starting to type in the current cell. The following two routines implement this:

Private Sub MSFlexGrid1_DblClick()
   GridEdit Asc(" ")
End Sub

Private Sub MSFlexGrid1_KeyPress(KeyAscii As Integer)
   GridEdit KeyAscii
End Sub

In each case we call a grid edit subroutine and pass it a keystroke. In the case of double-clicking, we pass the space character as a flag. The GridEdit routine initializes the edit box and moves it into position:

Sub GridEdit(KeyAscii As Integer)

   'use correct font
   Text1.FontName = MSFlexGrid1.FontName
   Text1.FontSize = MSFlexGrid1.FontSize

   Select Case KeyAscii
      Case 0 To Asc(" ")
         Text1 = MSFlexGrid1
         Text1.SelStart = 1000
      Case Else
         Text1 = Chr(KeyAscii)
         Text1.SelStart = 1
   End Select
   'position the edit box
   Text1.Left = MSFlexGrid1.CellLeft + MSFlexGrid1.Left
   Text1.Top = MSFlexGrid1.CellTop + MSFlexGrid1.Top
   Text1.Width = MSFlexGrid1.CellWidth
   Text1.Height = MSFlexGrid1.CellHeight
   Text1.Visible = True
End Sub

For demonstration purposes, the Case statement in the GridEdit routine shows two different behaviors when entering the edit mode. In practice you would probably only use one of them, or a different one of your own creation. If the edit mode is entered by virtue of a double-click or a control key press, we copy the contents of the grid cell to the exit box and place the cursor at the end of the string. If the edit mode is entered by pressing a normal key, we ignore the original cell contents and insert the pressed key into the edit box. The positioning of the exit box could be done on one line with the Move method. Here we have used four lines so that it reads more easily in this article. Notice that MSFlexGrid conveniently gives us all the coordinate information we need.

Next, we need a couple of routines that handle housekeeping when the user moves to a different cell or moves focus back to the grid from another control. The LeaveCell event is also the place where you would put any data validation code that might be applicable.

Private Sub MSFlexGrid1_LeaveCell()
   If Text1.Visible Then
      MSFlexGrid1 = Text1
      Text1.Visible = False
   End If
End Sub
Private Sub MSFlexGrid1_GotFocus()
   If Text1.Visible Then
      MSFlexGrid1 = Text1
      Text1.Visible = False
   End If
End Sub

Next we place some navigation code in the KeyDown event of the edit box so that, for instance, the user can leave the edit mode by pressing ESC, and move to a different row by pressing an arrow key:

Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
   Select Case KeyCode
      Case vbKeyEscape
         Text1.Visible = False
      Case vbKeyReturn
      Case vbKeyDown
         If MSFlexGrid1.Row < MSFlexGrid1.Rows - 1 Then
            MSFlexGrid1.Row = MSFlexGrid1.Row + 1
         End If
      Case vbKeyUp
         If MSFlexGrid1.Row > MSFlexGrid1.FixedRows Then
            MSFlexGrid1.Row = MSFlexGrid1.Row - 1
         End If
   End Select
End Sub

Finally we need a line of code to suppress the Beep that occurs when ENTER is pressed in a Textbox:

Private Sub Text1_KeyPress(KeyAscii As Integer)
   'noise suppression
   If KeyAscii = vbKeyReturn Then KeyAscii = 0
End Sub

In order for the edit box to merge seamlessly into the grid, you need to set several Textbox properties at design-time: set Appearance = 0 (flat), and BorderStyle = 0 (none). Also set Visible = False so that the edit box is not initially visible. To really fine-tune this code, the edit box needs a slight additional offset to the southeast (with a corresponding reduction in size) so that the text in it lines up exactly with the text in the cell beneath. You would probably also want to write some code behind the scroll event of the grid since clicking on the grid's scroll bar will not cause the edit box to loose focus.

Note that this technique is not limited to using a Textbox as your edit box. You could modify the sample code to use a ComboBox, a CheckBox, or even a calendar control for editing, based on the column being edited.

MSFlexGrid is a very flexible control indeed, and this article just touches on some of the things you can do with it. As you gain familiarity with it, it will become a more regular part of your toolbox. Cell merging and pivoting are two more unique features of the MSFlexGrid that give it tremendous power and bear investigation.


From:  Rodrigo Iloro
Date:  June 22,2000

I need to make a executable file who run in the cgi-bin of a web page. I'm have plans to make it in VB and I don't know how make a redirection of the standar input-output sistem. 

Also, any other idea will be hot! 

Thanks in advance and sorry about my english, 

Rodrigo from Argentina

The Guru's Response:

Hi Rodrigo, LOL, not to worry, your English is just fine.

Wow, it has been a long time since I have written a VB EXE for CGI stuff, at least 5 years.  I tried to look in my old back ups, but unfortunately I could not find anything to help you.  As far as I can remember, it is basically using the post method, with VB strings, to write out the HTML on the fly, so you should be able to just write out a redirect method too.  I know it is probably not much help, but I hope I pointed you in the right direction.

Hide a Program From The Operating System

From:  Kevin Taylor
Date:  June 21,2000

Is there any way to hide a program from the Operating system so that isn't detectable by other programs? (When you press alt ctrl del I don't want to be able to see it in the running applications)

The Guru's Response:

LOL...Ummmm.....Why would you want to do that? First of all, you will never be able to hide an application from the Operating System, but, how hidden from the User it is, depends on the Operating System the User is using; NT4/W2K is a lot harder to hide all traces then with Win9.x/Win Millennium.  Having said that, you can create an application with VB that will not show up in the Task Manager in Win9.x, and only show up in the processes section in NT/W2K, the user would have to know what they are looking for to find it.

Create a new Standard EXE, remove all forms from the project, check the "unattended execution" option in the project properties.  Next, add a bas module to your project and create a SUB called Main() to the Bas file. Last, but not least, set the start up of the project to your Sub Main().  Add all of your code to the project, you can create classes, call other COM objects ect. but you can not display any forms what so ever, that goes for the COM object that you call.  You are all set, It will not show up in the Win9.x Task Manager, and only show up in the Processes section of the NT/W2K Task Manager.  Please be careful, this should only be used for un-attended applications, like scheduled tasks, not malicious programming.

VB 4 Enterprise/Professional Edition to purchase

From:  Al Foster
Date:  June 20,2000

I'm trying to locate a copy of VB 4 Enterprise/Professional edition to purchase. It does not need to be a copy that can be registered. Just need to purchase the CD and key - documentation is not needed, but would be nice.  

Any leads you could provide me? 

Thanks for any help you can provide!!!!!

The Guru's Response:

Sorry Al, 
If I still had a copy kicking around, I would just give it to you, but Mrs. Guru made me clean out my closet about a year ago, and everything old went in the garbage.  If any one knows of where Al could get his hands on a copy, please email me at The Guru and I will pass the info on to Al.


Custom file type

From:  Z.C.
Date:  June 19,2000

How do you make a custom file type? (examples ".aaa" or ".bbb" etc.)

The Guru's Response:

It really depends on what you mean by a custom file type. It you mean create your own OLE file type, like the ones used in Word ect, that is way above what we could cover here. If this is the type of file you are trying to create, I would recommend finding a copy of the original W.O.S.A. (Windows Operating System Architecture) book from Microsoft Press.  This will teach you the basics of creating this type of file, including Linking and/or Embedding other files within your file.  If you just want to create a custom text file with the extension .aaa or .bbb, then use the Open # statement with the Print # or Write # statement to create the file. You pass the file name in the Open statement and call it what ever you want.  I have also created temporary Access files with a .tmp extension, that are created and destroyed during execution.  The .tmp extension is not associated with any application, but the OpenDatabase() will work correctly because the file is in fact an Access database.  To create a database in this fashion, just use the following: Set database = workspace.CreateDatabase (name, locale, options).


Opening a Crystal Report

From:  George Jurgowiak
Date:  June 16,2000

How do I create a "report" object that can be passed to the "crystal report smart viewer". I understand that you can bring up the viewer with the following statements (once the object has been placed in the VB form) : 

CRViewer1.ReportSource = Report CRViewer1.ViewReport 

I have a crstal report already created and know the report filename and path - just need to the create the "report" object - how is it defined ? 

Thanks George 

The Guru's Response:

Sorry George, it has been a while since I have used Crystal Reports, even then, I always used the version that shipped with VB.  This is usually at least one version less then the current shipping version, and I have a funny feeling you are using a newer version then the one that shipped with VB 6, version 4.5.  Any how, I pulled out some old code & refreshed myself with CR version 4.5, this is how you do it in that version, chances are, your version is going to be very similar.

  1. Add the Data control, ActiveX control, and a command button to your form.
  2. On the Data control, set the DatabaseName property and the RecordSource property as you did in the previous example.
  3. On the ActiveX control:

    Set the DataSource property to the Data Control, e.g: Data1.
    Set the ReportSource property to 3 - All Data Control Fields.
    Open the Custom property and select the Data-Bound Report Tab.
    Click on the Save Report As button and enter a name for the report.

  4. Open the report template in Crystal Reports and apply any formatting that you want including spacing between columns, font size, colors, grouping, and totaling. Save the report template again when finished.
  5. In your Visual Basic application, set the following properties for the ActiveX control:

    Set the ReportSource to 0 - Report File.
    Set the ReportFileName to the .RPT file that you saved (include the complete path of the file).

  6. On the command button, add the following code to the Click event:

    Private Sub Command1_Click() 
       CrystalReport1.Action = 1
    End Sub

Gaming with VB

From:  Christian Klein
Date:  June 16,2000

Dear Guru:

I have a problem in my current game project. The game should be a multiplayer-realtime-stratgy-game (like: Warcraft 2). And I have big trouble to write the routing for the units. What I need is a function that calculates the shortest way for units from point A to point B. And the units have to walk around buildings and trees and so an. If you wish I can send you a preview version of the MapEditor of my game. 

The Guru's Response:

Sorry Christian, although I am a huge on-line, game player, I do not have very much experience writing games.  When DirectX 7.x came out, I played around with the new VB interface a bit, just to see what you can do, but that is about it.  For all those aspiring game developers out there, you can download the DirectX 7.x SDK from Microsoft DirectX Developer Download Be prepared, it's 128MB download, but you can also order the CD version for a nominal fee.  It has tons of VB code samples, and I found it really neat to see how a 3D game is made.

Banner 10000016

Close Your Application

From:  Kevin Taylor
Date:  June 13,2000

Hey Guru:

Is there a command in VB that will shut down my program and close my form that I can call from a Sub??

The Guru's Response:

To close a form, call Unload FormName, so if you have a form called frm1, then call Unload frm1

To end an application, call, END, it is not advised to do this, you should have one exit point in your program only, that way you call all your application, clean up code first, before exiting.  The usual way is to call the unload to unload your main form, then perform your clean up from there. Examples of clean up code is to set all objects to nothing, delete all temp files you have created, close other open forms etc.

Open and start using applications

From:  khaled kaakati
Date:  June 08,2000

Hello Mr. Guru:

I have three Access data base called IPCS.mdb and ICTS.mdb and , BATA.mdb. Plus a FoxPro Based "outside vendor" application called PARAGON.EXE. I would like to give my uses the ability to open and start using these applications from one form menu by going to:


The Guru's Response:

In your project, create a reference to the Microsoft Shell Controls and Automation (...\system32\shell32.dll)

In the declaration section of your form, create a variable similar to this:

Dim MyShell As Shell32.Shell

In the Form_Initialize() or Form_Load() event, place this:

Set MyShell = New Shell32.Shell

Then, in the appropriate Menu_Click() event, place this code, but modify it to your path and file name:

MyShell.Open ("C:\My Documents\IPCS.mdb")

As you can see, I choose to use the Shell Object to open the file over the Shell() function, I personally feel it is more OOP centric coding.  If you check your VB Help File, for the Shell Object, you will see is has a tremendous amount of features, like Browsing for folders, Find Computers on the Network and opening Windows Explorer, for example.

Julian day format

From:  HercZ
Date:  June 08,2000

Hey guru, Is there a quick and easy function in VB to convert day format to Julian day format? So Dec. 31 will be 365?

The Guru's Response:

Place This code a form, BAS or class Mod:

We are using two functions that you have probably not used before, the IsDate and DateSerial functions. As you can see, the IsDate will return a Boolean value indicating if if the passed date is valid.  This is a good function to verify dates before inserting into a database, but in this case, it does the trick for checking if this is a leap year or not.  You should note that little piece of code, because it comes in handy. The DateSerial function call, which normally Returns a Variant (Date) for a specified year, month, and day, for example:

Dim MyDate
' MyDate contains the date for February 12, 1969.
MyDate = DateSerial(1969, 2, 12)   ' Return a date.

But, it can be modified for our purposes.

Update to this Question

From : HercZ
Date: June 09,2000

Well the Guru has learned something today, HercZ replied with this:

"i just tought of this
i found an easier way
i can just subtract the date from 1/1/current year
so subtract:

I never even thought of this, hope you do not mind Herc, but I took the liberty to create the full code for it, so here it is:

Public Function JulianDay(DayToCheck As Date) As Integer

  Dim ThisYear   As Date

  ThisYear  = "12/31/" & Year(Now()) 

 JulianDay = DayToCheck - ThisYear

End Function

Text Box KeyPress

From:  HercZ
Date:  June 01,2000

Hello guru, I have the following code for keypress method of a textbox: 

Private Sub txtMaxRoot_KeyPress(KeyAscii As Integer) Select Case Chr(KeyAscii) Case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "." Case Else KeyAscii = 0 End Select End Sub 

I want it to accept only numbers and period. My question is how do make it to accept backspace as well? I tried looking up ascii code for backspace but couldn't find it.... Thanks so much

The Guru's Response:

Place This code in the KeyPress Event of your TextBox:
Private Sub Text1_KeyPress(KeyAscii As Integer)

Select Case KeyAscii
Case 48 To 57, 46, vbKeyBack
KeyAscii = KeyAscii
Case Else
KeyAscii = 0
End Select

End Sub

Now, there are a few things you have learned here. The Select Case can compare not only a range of values in one statement, but you can also pass constants, mix & match them.  So in one statement, we have basicaly said, "if the number is between ASCII 48 - 57, the 0 - 9 decimal, or if it is the . (period), or the backspace, then everything is OK. If it is anything else, beep at the user and dump the key"

What is the meaning of life master?

From:  The Lost One
Date:  May 31, 2000

The Guru's Response:

I really do not want to get into philosophy here, this is a VB site. But I will answer this one question, and I do mean only, this one question. 

One, do you mind if I call you one? The meaning of life, in no particular order, is, VB Coding & Fragging in Unreal/Unreal Tournament.

Create the best code that you can, do not take short cuts, they will only come back to haunt you.  I do not care how good or experienced you are, a day that you have not learned something new in VB is a wasted day.

Always take time out in the day to capture the flag at least once. A day with out taking a break and doing something fun, is too stressful, and that can only lead to bad coding.

Resize Form

From:  HercZ
Date:  May 26,2000

Hi Guru,
I'm looking for code to resize forms, can u tell me how to do this?

The Guru's Response:

Add This code to a BAS file in your project:
Public Sub ElasticForm(ByRef frm As Form, ByVal Init As Boolean)
Dim ctl As Control
On Error Resume Next

If Init = True Then

For Each ctl In frm.Controls
ctl.Tag = Format$(ctl.Left / frm.ScaleWidth, ".0000") & Format$(ctl.Top / frm.ScaleHeight, ".0000") & Format$(ctl.Width / frm.ScaleWidth, ".0000") & Format$(ctl.Height / frm.ScaleHeight, ".0000")
Next ctl


For Each ctl In frm.Controls
If TypeOf ctl Is ComboBox Then
ctl.Move Val(Mid$(ctl.Tag, 1, 5)) * frm.ScaleWidth, Val(Mid$(ctl.Tag, 6, 5)) * frm.ScaleHeight, Val(Mid$(ctl.Tag, 11, 5)) * frm.ScaleWidth
ctl.Move Val(Mid$(ctl.Tag, 1, 5)) * frm.ScaleWidth, Val(Mid$(ctl.Tag, 6, 5)) * frm.ScaleHeight, Val(Mid$(ctl.Tag, 11, 5)) * frm.ScaleWidth, Val(Mid$(ctl.Tag, 16, 5)) * frm.ScaleHeight
End If
Next ctl
End If

End Sub

Place This code in the Load event of your form:
Do Events
ElasticForm Me,True

Place This code in the Resize Event of your Form:
If Not Me.Visible = False Then ElasticForm Me, False


Send mail to WebMaster with questions or comments about this web site.
This website is best viewed with a screen resolution of 800*600 or better.
This website is optimized for Microsoft Internet Explorer 6.x
K&K Consulting, Proud to be a Microsoft Business Partner.
Last modified: January 31, 2002