Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

open & close EXCEL with VB6

Hi all,
I have a picture with part numbers on it. I placed invisible "labels" over each part number. The company that we get the parts from sends us a disk with prices in Excel format. I want to be able to click on the picture and have it open the Excel file, highlight the part and price, and be able to close the Excel window so my picture is visible again. From here I want to be able to click on another part and repeat the process as many times as needed to look up all parts used.
Nomatter what I try I can only open Excel once, sometimes twice, and then the program refuses to cooperate. Here is some of the code that I have tried:
Dim AppExcel As Excel.Application

Private Sub Form_Load()
Set AppExcel = CreateObject("Excel.Application")
ChDir "D:\"
Workbooks.Open FileName:="D:\K and D (152598).xls"
End Sub

Each Lable Has It's Own Click Event

Private Sub lbl034_Click()
Workbooks.Open FileName:="D:\K and D (152598).xls"
Cells.Find(What:="34034b", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
'Highlights the entire row.
If IsEmpty(ActiveCell) Then Exit Sub
On Error Resume Next
If IsEmpty(ActiveCell.Offset(0, -1)) Then Set LeftCell = ActiveCell Else Set LeftCell = ActiveCell.End(xlToLeft)
If IsEmpty(ActiveCell.Offset(0, 1)) Then Set RightCell = ActiveCell Else Set RightCell = ActiveCell.End(xlToRight)
Range(LeftCell, RightCell).Select

AppExcel.Visible = True
End Sub

This code will open Excel and highlight the row once. When I close the Excel window and try clicking on another part an Excel window opens but it is blank even if I click the same part that just opened up perfectly the first time. I have been fighting with this for months. Any suggestions?
Thanks in advance, Garner
[2022 byte] By [Garner] at [2007-11-11 8:26:17]
# 1 Re: open & close EXCEL with VB6
First remark, you use a mix of methods. I doubt if you get any result...
I will reform your code a little bit, because this isn't working. I think you have recorded a macro in excel and then paste it in your VB6.0, this isn't good.
Benjamin at 2007-11-11 17:25:33 >
# 2 Re: open & close EXCEL with VB6
This should give you a start, to open your excel:

Dim AppExcel As Object

Set AppExcel = CreateObject("Excel.application")

AppExcel.Workbooks.Open "D:\K and D (152598).xls"
AppExcel.Visible = True
Benjamin at 2007-11-11 17:26:33 >
# 3 Re: open & close EXCEL with VB6
Benjamin,
You are correct both times. I have a terrible mix of code from commenting out, re-writing, copy and paste, and anything else I could think of to try to make this work. I also did record a "find next" macro and pasted it into my code.
I'm not a very good programmer. What I know I learned from books that I bought and from helpful people like yourself. I will try your suggestion as soon as I can and post the results.
Thanks for your time! Garner
Garner at 2007-11-11 17:27:31 >
# 4 Re: open & close EXCEL with VB6
Benjamin,
Thanks for trying to help! However I am still having no luck. I tried what you suggested and now it won't even open excel the first time. I don't understand why the code that I originally used would work perfectly the first time but as soon as I close the Excel window and try again it don't work?! I'm not going to give up! The answer is out there and I'll find it or die trying.
Thanks again, Garner
Garner at 2007-11-11 17:28:36 >
# 5 Re: open & close EXCEL with VB6
Garner,

do you get any error? The code works fine by me, if it isn't working for you, you should at least get an error message.
Benjamin at 2007-11-11 17:29:37 >
# 6 Re: open & close EXCEL with VB6
Benjamin,
This is another thing that I don't understand. I commented out all of my error handeling in hopes that it would lead me to the problem. Thing is, it don't generate any errors! With my original code the program opens Excel, finds the product, and highlights the entire row. I close the Excel window, click on a number, and excel opens again but this time only a gray background or a blank frame. I can close this window and my picture re-appears with no errors, no freeze up, nothing.
When I tried what you suggested, nothing happened. I clicked the picture and the picture was still there, no errors, no freeze up, nothing. It don't make any sense! Another guy sent me some really fancy code with a module to detect if Excel was running, error handlers, the works. He commented a spot in his code where I was supposed to paste my "find next" code. I done what he said and it worked just like my code. Opened once perfectly, then nothing.
I'm still thinking, reading, and pulling my hair out. This should be so easy but it's becomming a real challenge.
Thanks again, Garner
Garner at 2007-11-11 17:30:36 >
# 7 Re: open & close EXCEL with VB6
Have you thought about importing the excel sheet into access table create a field in access and place the values of each "Part" into that column then when the label is clicked, display a window with the part information

i added 2 events
mouse over while you move over each image the info in form 2 changes.
Click event click the label results inthe window opening withthe info
comment out the mouseover event and use ther Click event

Run the exe to see or view the souce files then run the exe
see attached and enjoy !
jim12345 at 2007-11-11 17:31:39 >
# 8 Re: open & close EXCEL with VB6
Hi,

the only thing I can imagine is that your instant of excel isn't opened correctly. So I've checked your first code and this solution should work much better:

'Dim AppExcel As Excel.Application

Private Sub lbl034_Click()
Set AppExcel = CreateObject("Excel.Application")
AppExcel.Workbooks.Open FileName:="g:\tmp\book11.xls"

Cells.Find(What:="34034b", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate

'Highlights the entire row.
If IsEmpty(ActiveCell) Then Exit Sub

On Error Resume Next
If IsEmpty(ActiveCell.Offset(0, -1)) Then Set LeftCell = ActiveCell Else Set LeftCell = ActiveCell.End(xlToLeft)
If IsEmpty(ActiveCell.Offset(0, 1)) Then Set RightCell = ActiveCell Else Set RightCell = ActiveCell.End(xlToRight)
Range(LeftCell, RightCell).Select

AppExcel.Visible = True
End Sub

Private Sub Form_Load()
'Set AppExcel = CreateObject("Excel.Application")
'Workbooks.Open FileName:="g:\tmp\book11.xls"
End Sub

First of all dim appExcel above should be deleted is not the method we use.
The code in the form_load has to be deleted also.
To open a workbook don't use only workbooks.open, but app.excel.workbooks.open

Check this code and let me know the outcome.
Benjamin at 2007-11-11 17:32:39 >
# 9 Re: open & close EXCEL with VB6
Jim,
That is one fantastic program! I think that you are lightyears ahead of anything that I can do. I also don't know how it would work for what I am trying to accomplish. I am trying to make things as simple as possible for people who know even less about computers than myself. You see, our supplier sends a new price list every couple of months. I was hoping that anyone in the shop could just throw the disk in drive D: and come up with a current price. The disks are already in .xls format. I don't even know if I could convert things over properly to make your program work? That may take me a couple more years of learning. And then, even if I could do it, the rest of the shop would be screwed if anything ever happened to me.

Nomatter what I use at the shop I can see that I will have a ton of fun learning new things from all of that great code you provided!!!

Benjamin,
I copied and pasted your code into my project and deleted all of mine. First run, I found that I had to change :="g:\tmp\book11.xls" to my destination of "D:\K and D (152598).xls". Second run, 1st click, Excel opened and the proper line was highlighted. Closed Excel, picture was visible, so I clicked the same part over again. This time there was an error.

Error #1004 Method 'cell's of Object' Global' Failed

This part of the code was highlighted:

Cells.Find(What:="34034b", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate

I am going to look up what this means after I submit this reply. At least now there is an error message that could lead to a solution to the problem. That is more than I had to go on before!

Thanks a million to both of you!!!! Garner
Garner at 2007-11-11 17:33:36 >
# 10 Re: open & close EXCEL with VB6
I see your point with wanting it to be easy to use.. if they update the picing every few months, you could make a copy of database, let them continue with what they have and then cut over to a dtabase style. how much time are we talking from the point they click the image till excel is opened, what if they click another image while excel is still open?

as for the data, you could write a import routine to import the data from the CD to the database.
jim12345 at 2007-11-11 17:34:37 >
# 11 Re: open & close EXCEL with VB6
Hi again Jim,
(J) I see your point with wanting it to be easy to use.. if they update the picing every few months, you could make a copy of database, let them continue with what they have and then cut over to a dtabase style.
(G) That was kind of my plan. Get the project I started to work, let them use it, and that would give me time to study your design.

(J) how much time are we talking from the point they click the image till excel is opened,
(G) When it works, it takes less than a second for the highlighted information to show up in the Excel window.
(J) what if they click another image while excel is still open?
I think I have that problem covered. I set the Excel window to open maximized. This covers up my picture preventing them from clicking another part until they close the Excel window.
(J)as for the data, you could write a import routine to import the data from the CD to the database.
(G) Yes, I would like to do this. Just keep in mind that I write programs because I like learning. I really dont know how to do that yet so that would be a new learning adventure. I also have to do this learning in very limited time. I have been working ten hour days, rush home to grab a quick meal and take the girls to basketball, softball, dance, or whatever is on the agenda for the evening, and still have time with my wonderful wife. This leaves me very little time for programming or even replying to all of the great people, like you, that Ive met through these forums. Someday life might slow down enough that I can learn how to write a cool program like the one that you sent to me.
Thanks again, Garner
Garner at 2007-11-11 17:35:37 >
# 12 Re: open & close EXCEL with VB6
Hi all,
So far, nothing has resolved my problem. I have some new code that you might want to look at.

This is a module to detect Excel.

' Declare necessary API routines:
Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName As String, _
ByVal lpWindowName As Long) As Long

Declare Function SendMessage Lib "user32" Alias _
"SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long

Public Sub DetectExcel()
' Procedure dectects a running Excel and registers it.
Const WM_USER = 1024
Dim hWnd As Long
' If Excel is running this API call returns its handle.
hWnd = FindWindow("XLMAIN", 0)
If hWnd = 0 Then ' 0 means Excel not running.
Exit Sub
Else
' Excel is running so use the SendMessage API
' function to enter it in the Running Object Table.
SendMessage hWnd, WM_USER + 18, 0, 0
End If
End Sub

This is the main code.

Private Sub Form_Activate()
p4l80e.SetFocus
End Sub

Private Sub lbl034_Click()
'On Error GoTo erh

Dim MyXL As Object ' Variable to hold reference to Microsoft Excel.
Dim ExcelWasNotRunning As Boolean ' Flag for final release.

' Test to see if there is a copy of Microsoft Excel already running.
On Error Resume Next ' Defer error trapping.
' Getobject function called without the first argument returns a
' reference to an instance of the application. If the application isn't
' running, an error occurs.
Set MyXL = GetObject(, "Excel.Application")
If Err.Number <> 0 Then ExcelWasNotRunning = True
Err.Clear ' Clear Err object in case error occurred.

' Check for Microsoft Excel. If Microsoft Excel is running,
' enter it into the Running Object table.
DetectExcel

Set MyXL = GetObject(App.Path & "\K and D (152598).xls")

' Show Microsoft Excel through its Application property. Then
' show the actual window containing the file using the Windows
' collection of the MyXL object reference.
MyXL.Application.Visible = True
MyXL.Parent.Windows(1).Visible = True


Workbooks.Open FileName:="D:\K and D (152598).xls"
Cells.Find(What:="34034b", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
'Highlights the entire row.
If IsEmpty(ActiveCell) Then Exit Sub
On Error Resume Next
If IsEmpty(ActiveCell.Offset(0, -1)) Then Set LeftCell = ActiveCell Else Set LeftCell = ActiveCell.End(xlToLeft)
If IsEmpty(ActiveCell.Offset(0, 1)) Then Set RightCell = ActiveCell Else Set RightCell = ActiveCell.End(xlToRight)
Range(LeftCell, RightCell).Select

Exit Sub
erh: MsgBox Error(Err)
End Sub

This code works perfectly the first time I click a label. When I close the Excel window and click the label a second time, the Excel window just flashes on the screen for a half second and I'm back at the start screen. No matter how many times you click the label from this point Excel only flashes on the screen, then off, like the close button has been clicked. I even tried placing a message box at different points in the main code. That didn't work either.
This code produces no errors, no freeze ups, and no crashes. It just won't keep the Excel window open after the first click. How is that possible when I click the same label that is using the same code that just worked? :confused:

Thanks again to everyone who has offered help! Garner
Garner at 2007-11-11 17:36:46 >
# 13 Re: open & close EXCEL with VB6
set a break point on thr click event of the label and run your app. ater the first run through, click the same label again and seee what happens.

As a side note, have you thought of using acess like the example I gave you?
Converting your existing app to use access will be easy...
make a reference to ADO
use the sub main i sent you.
open access and import your data into a new table using the wizard. (yup it will create the table for you)
point the above submain to point to the new database & table.
Change the event for the labels to search the database and display the info

When suppliers send you a updated price sheet, rename the existing table & simply import the data again

No code changes are needed since the table name will always be the same.
jim12345 at 2007-11-11 17:37:41 >
# 14 Re: open & close EXCEL with VB6
This code works perfectly the first time I click a label. When I close the Excel window and click the label a second time, the Excel window just flashes on the screen for a half second and I'm back at the start screen.

It looks to me like your Excel object is going out of scope after the Click event terminates. This could explain the behavior you are seeing.

If you want Excel to remain open and visible I would create your Excel object outside of the Click event. Otherwise you may end up with several instances of Excel running that are not visible (because Excel isn't being terminated properly). You can verify whether this is happening by looking for Excel processes in the Task Manager.
pclement at 2007-11-11 17:38:44 >
# 15 Re: open & close EXCEL with VB6
Jim,
Thanks again for the advice. I will try the "Break Point" thing and let you know what happens.
As to trying an ADO program, YES, I want to try it. I wrote a large database program 5 years ago for a friend and his company is still using it to this day. The differance was that all data is input manually and I constructed the databases from scratch. "Wizards" and "Import Data" will be all new to me. Even if I could get my current project working I still want to learn something new. I guess I just want to understand what is going on with the one I started before I tackel somethin new. I need to learn what is causing the problem if I'm going to avoid similar problems in the future.
Thanks again and I'll update any progress I make, Garner

Paul,
When I first started having this problem I put this code:

Dim MyXL As Object ' Variable to hold reference to Microsoft Excel.
Dim ExcelWasNotRunning As Boolean ' Flag for final release.

' Test to see if there is a copy of Microsoft Excel already running.
On Error Resume Next ' Defer error trapping.
' Getobject function called without the first argument returns a
' reference to an instance of the application. If the application isn't
' running, an error occurs.
Set MyXL = GetObject(, "Excel.Application")
If Err.Number <> 0 Then ExcelWasNotRunning = True
Err.Clear ' Clear Err object in case error occurred.

' Check for Microsoft Excel. If Microsoft Excel is running,
' enter it into the Running Object table.
DetectExcel

Set MyXL = GetObject(App.Path & "\K and D (152598).xls")

' Show Microsoft Excel through its Application property. Then
' show the actual window containing the file using the Windows
' collection of the MyXL object reference.
MyXL.Application.Visible = True
MyXL.Parent.Windows(1).Visible = True


Workbooks.Open FileName:="D:\K and D (152598).xls"

in my "Form Activate" event thinking that it might solve the problem and also save a lot of code in each label event. The program would error as soon as the label was clicked. I think the error was "Global Variable Failed." I tried several variations, same code in the "Form Load" event, split the code between "General Declarations" & "Form Activate", and half a dozen other things. Always said that the Global Failed.
As to several instanses of Excel running, I watched what you said. Excel blinks in the task bar and right back out just like the Excel window on the screen. I will try looking on the "Task Manager" as you suggested and get back with the results.
Thanks for the advice! I'll keep trying, Garner
Garner at 2007-11-11 17:39:47 >
# 16 Re: open & close EXCEL with VB6
Once again, definining a variable in a Sub, Function, Event, etc will localize it to that routine. Once that routine terminates the variable is out of scope and destroyed. If you don't properly terminate the application to which that variable points to before it is destroyed there is a good chance that the application will remain in memory. This could cause problems upon re-use or creation of a new instance of the application.

I would either terminate Excel (Quit method) before the routine finishes executing, or declare a global or module level variable for your Excel object and then terminate it when your application terminates.
pclement at 2007-11-11 17:40:42 >
# 17 Re: open & close EXCEL with VB6
To "Super Paul",
I think you figured out how to fix my program!!!!! I studied your suggestion,

I would either terminate Excel (Quit method) before the routine finishes executing, or declare a global or module level variable for your Excel object and then terminate it when your application terminates.

I really didn't know how to do this but I tried adding,

On error resume next
MyXL.Application.Quit
Set MyXL = Nothing

to my form activate event. I ran several short tests and it worked perfect!!! I need to do some more tests but I was so excited that I just had to let you know. Thanks for all of the help, Paul & EVERYONE who spent time and effort tryin to figure this out!
Garner
Garner at 2007-11-11 17:41:50 >
# 18 Re: open & close EXCEL with VB6
Sorry everyone,
I spoke to soon. I went back to testing the program and it's right back to the same thing as before. I guess I'll start reading on how to declare a global or module level variable for your Excel object and then terminate it when your application terminates.
Back to work, Garner
Garner at 2007-11-11 17:42:43 >