473,804 Members | 2,292 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Automation Problem

I have a problem with the following code, which leaves an instance of
Excel visible in Task Manager.

By a process of elimination I have got it down to the fact that
something in the DoCmd.Transfer Spreadsheet line is holding on to an
Excel reference somewhere - can anybody assist (if I comment this line
out, the instance is released, and not visible in Task Manager).

Private Sub btnLoadData_Cli ck()
Dim xlApp2 As Object
Dim xlBook As Workbook
Dim xlSheet As Worksheet
Dim strFilename as string
Set strfilename = "c:\test.xl s"
Set xlApp2 = CreateObject("E xcel.Applicatio n")
xlApp2.Visible = True
Select Case Me.Data_File_Fr om
Case "West Herts"
xlApp2.Workbook s.Open FileName:=strFi leName,
Password:="barb ados"
Case "Luton"
xlApp2.Workbook s.Open FileName:=strFi leName
Case "Stoke Mand"
xlApp2.Workbook s.Open FileName:=strFi leName,
Password:="amer sham"
Case "South Bucks"
xlApp2.Workbook s.Open FileName:=strFi leName,
Password:="amer sham"
Case "South Bucks Susp"
xlApp2.Workbook s.Open FileName:=strFi leName,
Password:="amer sham"
End Select

DoCmd.TransferS preadsheet , , strImportTableN ame, strFileName, True

xlApp2.Workbook s.Close
fCloseApp ("XLMain")

Set xlBook = Nothing

xlApp2.Quit
Set xlApp2 = Nothing

End Sub
Function fCloseApp(lpCla ssName As String) As Boolean

Dim lngRet As Long, hWnd As Long, pID As Long

hWnd = apiFindWindow(l pClassName, vbNullString)
If (hWnd) Then
lngRet = apiPostMessage( hWnd, WM_CLOSE, 0, ByVal 0&)
Call apiGetWindowThr eadProcessId(hW nd, pID)
Call apiWaitForSingl eObject(pID, INFINITE)
fCloseApp = Not (apiIsWindow(hW nd) = 0)
End If
End Function

Thanks

Gary
Nov 13 '05 #1
5 4148
I have been down this EXACT same road many a time and had the EXACT same
problem as you and used the EXACT same api code to try to close that
instance of Excel :). I finally found a solution that seems to work
between 99-100% of the time.

First, I would make the TransferSpreads heet call and then I would do the
CreateObject thing after TransferSpreads heet.

Second, instead of using an Object variable for xlApp2, I would make a
reference to your Excel Library (incase you haven't already) and
dimension your vars like this:

Dim xlApp2 As Excel.Applicati on
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.WorkSheet

Then you can use CreateObject(.. .). Note that I did not use the New
keywork in the Dim statements. I have tried New without CreateObject
but had issues. If you just reference the vars as I did and use
CreateObject, then xlApp2.Quit will really quit and no more Excel in
Task Manager. Plus, you get intellisense dropdowns this way.
Rich

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 13 '05 #2

"Gary Cobden" <ga*********@nh s.net> wrote in message
news:4a******** *************** ***@posting.goo gle.com...
I have a problem with the following code, which leaves an instance of
Excel visible in Task Manager.

By a process of elimination I have got it down to the fact that
something in the DoCmd.Transfer Spreadsheet line is holding on to an
Excel reference somewhere - can anybody assist (if I comment this line
out, the instance is released, and not visible in Task Manager).

Private Sub btnLoadData_Cli ck()
Dim xlApp2 As Object
Dim xlBook As Workbook
Dim xlSheet As Worksheet
Dim strFilename as string
Set strfilename = "c:\test.xl s"
Set xlApp2 = CreateObject("E xcel.Applicatio n")
xlApp2.Visible = True
Select Case Me.Data_File_Fr om
Case "West Herts"
xlApp2.Workbook s.Open FileName:=strFi leName,
Password:="barb ados"
Case "Luton"
xlApp2.Workbook s.Open FileName:=strFi leName
Case "Stoke Mand"
xlApp2.Workbook s.Open FileName:=strFi leName,
Password:="amer sham"
Case "South Bucks"
xlApp2.Workbook s.Open FileName:=strFi leName,
Password:="amer sham"
Case "South Bucks Susp"
xlApp2.Workbook s.Open FileName:=strFi leName,
Password:="amer sham"
End Select

DoCmd.TransferS preadsheet , , strImportTableN ame, strFileName, True

xlApp2.Workbook s.Close
fCloseApp ("XLMain")

Set xlBook = Nothing

xlApp2.Quit
Set xlApp2 = Nothing

End Sub
Function fCloseApp(lpCla ssName As String) As Boolean

Dim lngRet As Long, hWnd As Long, pID As Long

hWnd = apiFindWindow(l pClassName, vbNullString)
If (hWnd) Then
lngRet = apiPostMessage( hWnd, WM_CLOSE, 0, ByVal 0&)
Call apiGetWindowThr eadProcessId(hW nd, pID)
Call apiWaitForSingl eObject(pID, INFINITE)
fCloseApp = Not (apiIsWindow(hW nd) = 0)
End If
End Function

Thanks

Gary


Wthout commenting on the DoCmd.TransferS preadsheet, your procedures need to
implement error handling. This is pasted from a reply a recently posted on
the same issue:
Here is an example of some error handling which calls xlApp.Quit if an error
occurs (e.g. trying to open a non-existant workbook) but only if the
instance of Excel was one that the code created - ie Excel was not already
running:

Sub OpenWorkbook()

On Error GoTo Err_Handler

Dim xlApp As Object
Dim xlBook As Object
Dim blnError As Boolean
Dim blnNewApp As Boolean

' Switch off normal error handling as we
' attempt to use ruuning instance of Excel
' If Excel is not running, we try to start an instance
On Error Resume Next
Set xlApp = GetObject(, "Excel.Applicat ion")
If Err.Number <> 0 Then
Err.Clear
Set xlApp = CreateObject("E xcel.Applicatio n")
If Err.Number <> 0 Then
blnError = True
MsgBox "Error starting Excel", vbCritical, "Error"
GoTo Exit_Handler
Exit Sub
Else
blnNewApp = True
End If
End If

' Switch normal error handling back on
On Error GoTo Err_Handler

Set xlBook = xlApp.Workbooks .Open("C:\Test. xls")

xlApp.Visible = True
Exit_Handler:

On Error Resume Next

If Not xlBook Is Nothing Then
Set xlBook = Nothing
End If

If Not xlApp Is Nothing Then

If blnError And blnNewApp Then
xlApp.Quit
End If

Set xlApp = Nothing

End If

Exit Sub

Err_Handler:
blnError = True
MsgBox Err.Description , vbExclamation, "Error No: " & Err.Number
Resume Exit_Handler

End Sub
Nov 13 '05 #3
Hi Rich

Thanks for your suggestion – which I hoped was going to work

Unfortunately, if I use the CreateObject statement after the Transfer
Spreadsheet as suggested, I get error 3161 – Could not decrypt file

Any further suggestions?

Thanks

Gary


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 13 '05 #4
Hi Gary,

Yes, I do have another suggestion. I steer away from
TransferSpreads heet because of the very issue you describe. I use ADO
when I pass data to Excel. This technique is a little more
sophisticated than TransferSpreadS heet but offers a lot more control and
reliability. I will give you a sample code below. First, you need to
make sure you have Mdac2.5 and Mdac2.6 loaded on the computer you will
run this code. Mdac2.5 is the last version of Mdac that contains Jet
for interfacing with Access. Mdac2.6 is an upgrade for 2.5 which really
makes a difference in the ADO code useability. I think if you load 2.6
without having 2.5, the ADO may not work. You should be able to find
Mdac at MSDN or Google. Anyway, you make a reference in Tools/References
to Microsoft ActiveX Data Objects 2.6. Then here is the sample code:

-----------------------------------------------------------
Sub DataToExcelADO( )
Dim DB As Database, RS1 As Recordset, strSql As String
Dim j As Integer, t As Integer, RetVal as Variant
Dim cn As New ADODB.Connectio n, RS As New ADODB.Recordset

Set DB = CurrentDb

strSourcePath = Left(DB.Name, Len(DB.Name) - Len(Dir(DB.Name )))
strSourcePath = strSourcePath & "testExcel.xls; "
RS.CursorLocati on = adUseClient
cn.Mode = adModeReadWrite
cn.Open "Provider=Micro soft.Jet.OLEDB. 4.0;" & _
"Data Source=" & strSourcePath & _
"Extended Properties=""Ex cel 8.0;HDR=NO;"""

'---clear old data first
DoEvents
For j = 2 To 50 'clear old data from Excel Sheet
strSql = "SELECT * FROM [Sheet1$A" & j & ":U" & j & "]"
RS.Open strSql, cn, adOpenDynamic, adLockPessimist ic
For k = 0 To RS.Fields.Count - 1: RS(k) = Null: Next
RS.Update
RS.Close
Next

'---populate Sheet1
Set RS1 = DB.OpenRecordse t("tblTestData" )
f = RS1.Fields.Coun t
j = 2
DoEvents
Do While Not RS1.EOF
strSql = "SELECT * FROM [Sheet1$A" & j & ":U" & j & "]"
RS.Open strSql, cn, adOpenDynamic, adLockPessimist ic
For k = 0 To RS1.Fields.Coun t - 1
RS(k) = RS1(k)
Next
RS.Update
RS.Close
j = j + 1
RS1.MoveNext
t = t + 1
RetVal = SysCmd(acSysCmd SetStatus, t)
Loop
RS1.Close
cn.Close
End Sub
---------------------------------------------------------

Note that this technique does not use automation. You are referencing a
specific Excel workbook to write to. You can't do that with
TransferSpreads heet. There are a few Gotcha's though. First, you have
to pre-populate the Excel sheet you are going to write to, save, then
delete the fake data. This preps the sheet for ADO. Then usually, you
can leave the cells in General format, but sometimes ADO complains if
you write data from a Date/Time field in an Access Table. So format
those columns in Excel as Date or Time.

The next Gotcha is that ADO will only write one row at a time to Excel.
If you try Select * from your table of 500 rows, it will write the first
row 500 times to Excel. So you have to close the ADO recordset var RS
for each row. But it is lightening fast. You can write 500 rows in
about 5 seconds, if that. Also note, that for the Excel file that I
reference, you have to end it with a semi colon ";"

strSourcePath = strSourcePath & "testExcel.xls; "

Then, the sql statement

strSql = "SELECT * FROM [Sheet1$A" & j & ":U" & j & "]"

references the sheet you will write to. You can name the sheet anything
you want in Excel, but you have to use the same name in this sql
statement. I am writing here to columns A through U. j is the row
counter. Note in the example code, I start j at Row 2 then I increment
j. I also use

RetVal = SysCmd(acSysCmd SetStatus, t)

to monitor the progress of the Do Loop. SysCmd write to the status bar
at the bottom of Access. But back to the sql statement, you can write
your data to any column, row you want by referencing it in the sql
statement

strSql = "SELECT * FROM [Sheet1$H" & j & ":AD" & j & "]"

This write to columns H through AD. Just make sure you have the same
number of columns in your table. Just a word of FYI, ADO is very
touchy. It does a lot of complaining about data types. So start out
with just text fields, like say a table with 5 columns of text. So your
sql statement would be

strSql = "SELECT * FROM [Sheet1$A" & j & ":E" & j & "]"

The Excel workbook can be open or close. Works much faster if the
workbook is closed. Once you are done passing your data, you can then
use automation to do other stuff. I do this all the time.

HTH
Rich


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 13 '05 #5
>>
You are referencing a specific Excel workbook to write to. You can't do
that with TransferSpreads heet.
<<

Correction: You can reference a specific workbook with
TransferSpreads heet, but you can't re-use that workbook unless you
delete the TransferSheet first because TransferSpreads heet doesn't
overwrite. You don't have this problem with the ADO method. ADO will
write to any sheet you reference, and/or overwrite. Word of Caution, if
you pass 500 rows of data with ADO and then pass 300 rows another day,
you still have 200 old rows left over. So you need to clear out the old
data first. I usually, prep a worksheet for 10,000 rows with fake data
-- ";lkj;lkj;" --, save the workbook, then delete the fake data and save
again. The workbook will server as a template workbook (but not really
a template, not .xlt, just xls - once you pass your data use automation
to save the workbook as something else). Note: Prep Date/Time columns
with date/time data 1/1/1900, 00:05 and drag that down for 10,000 rows,
then delete.

Rich

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 13 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
5851
by: qwweeeit | last post by:
Hi all, Elliot Temple on the 1 June wrote: > How do I make Python press a button on a webpage? I looked at > urllib, but I only see how to open a URL with that. I searched > google but no luck. > For example, google has a button <input type=submit value="Google > Search" name=btnG> how would i make a script to press that button? I have a similar target: web automation, which
25
3750
by: Neil Ginsberg | last post by:
I have a strange situation with my Access 2000 database. I have code in the database which has worked fine for years, and now all of a sudden doesn't work fine on one or two of my client's machines. The code opens MS Word through Automation and then opens a particular Word doc. It's still working fine on most machines; but on one or two of them, the user is getting an Automation Error. The code used is as follows: Dim objWord As...
12
5539
by: Cheval | last post by:
Has anyone had any problems with inter-office automation between MS Word and MS Access in Office 2003? I have recently installed office 2003 in a new folder and have left the older office 2000 and office XP components installed. ie I have word/access/excel 2k/xp/2003 installed. I tried to do a usual access 2k to word 2k automation yet I get the error "Automation Error" "ClassFactory cannot supply requested class" when on late binding try...
1
808
by: Jimmer | last post by:
I've got what should be an easy automation problem, but the solution simply isn't coming to me. I've got several public variables set up for automation as follows: Public gappExcel As Excel.Application 'ADO Object for Excel Automation Public gstrExcelDir As String 'Source or Destination Directory
4
7688
by: Daniel | last post by:
Hello, i have a problem with the word automation from c#. First, i want to mention, that i don't have any dependencies from word in my c#-project, i want to use the system.reflection model to handle the automation. So, i'm using the following code to create a new word document: ---Code---
2
1564
by: Alfredo Magallón Arbizu | last post by:
Hello, I have an ASP.NET application that reads an Excel file through automation. The app has a loop until first cell of a row is blank. While the app works perfectly under Windows 2003, it fails under Windows 200 (Bad Variable Type, Interop.COMException) Same versions of Office (XP) on both machines.
16
2981
by: RichardP | last post by:
Hi there everyone - I'm new to this forum. I am having an issue when running an application from an instance of Access which has been started through automation (early or late bound, makes no difference). No warning / confirmation messages are issued (eg. when running action queries, deleting records from a datasheet, deleting database objects such as tables).
12
1649
by: Tomas | last post by:
Hi, I have worked with VB.NET for half a year (semi-newbie). Currently I am looking around for some books for those that crossed the starting hurdle. There are too many books out there-make choosing, a bit of a gamble. If you have experience of good VB.NET books on general and office automattion, you could recommend, it would be greatly appreciated.
0
9319
by: Sharath | last post by:
Quality Globe is Glad to Offer you the Fast Track course on Automation, QTP Basics and Advanced, and Quality Center Starting Date: June 4th, 2007 Timings: 10 AM to 3:30 PM Duration: 50 Hours Location: BTM Layout 1st Stage, Bangalore
0
2389
by: Sharath | last post by:
"Inspired" by the huge success of our first two automation fast track batches We are forced to start third fast track automation batch ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++ Course on Automation, QTP Basics and Advanced, Quality Center and project ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
0
9591
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10331
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10087
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9166
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6861
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5529
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.