controling excel from vba access and using sub procedures

Hi All,
I'm having trouble getting my code to work using sub procedures in my vba
code, this only happens when i am interacting with excel. I've tried to copy
all the dims and defs from the calling procedure but to no avail at this time.
sample code below.

Dim strPath As String
Dim rst As DAO.Recordset
Dim Excel_Application As Excel.Application
Dim Excel_Workbook As Excel.Workbook
Dim Current_Worksheet As Excel.Worksheet
Dim Data_Range
Dim Worksheet_Name
Dim db As Database
Dim rs As Recordset
D_now = Format(Date, "dd-mm-yy") ' Formated to use as part of file name
gg = "C:\Employee Time Report " & D_now & ".xls"
Is_File= Len(Dir(gg))
If Is_File= 0 Then
Else
    T_Msg = MsgBox("File already exists, Delete file and continue ?.",
vbYesNo, "")
    If T_Msg = vbYes Then
        Kill gg
    Else
        Exit Sub
    End If
End If
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Report Output",
gg, True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Comments", gg,
True
Set Excel_Workbook = GetObject(gg)
Set Excel_Application = Excel_Workbook.Parent
Excel_Application.WindowState = xlMinimized
Excel_Application.Visible = True
Excel_Workbook.Windows(1).Visible = True
Excel_Workbook.Worksheets(1).Name = "Report Output"
Set Current_Worksheet = Excel_Workbook.Worksheets("Report Output")
Excel_Workbook.Worksheets("Report Output").Select

THE code here works if left here but not in it's own sub procedure.- 'CAll
Add_Comments'

    Current_Worksheet.Range("B11").AddComment
    Current_Worksheet.Range("B11").Comment.Visible = False
    Current_Worksheet.Range("B11").Comment.Text Text:="trevorc:" & Chr(10) &
"test"

I was hoping to then add code to this sub procedure.

-- 
Message posted via AccessMonster.com
http://www.accessmonster.com/Uwe/Forums.aspx/access-modules/201002/1

0
trevorC
2/1/2010 9:05:49 AM
access.modulesdaovba 1670 articles. 0 followers. Follow

3 Replies
869 Views

Similar Articles

[PageSpeed] 10

hi Trevor,

On 01.02.2010 10:05, trevorC via AccessMonster.com wrote:
> THE code here works if left here but not in it's own sub procedure.- 'CAll
> Add_Comments'
>
>      Current_Worksheet.Range("B11").AddComment
>      Current_Worksheet.Range("B11").Comment.Visible = False
>      Current_Worksheet.Range("B11").Comment.Text Text:="trevorc:"&  Chr(10)&
> "test"
>
> I was hoping to then add code to this sub procedure.
It works if you define it correctly:

Public Sub AddComments(AWorkSheet As Excel.Worksheet)

   AWorkSheet.Range("B11").AddComment
   AWorkSheet.Range("B11").Comment.Visible = False
   AWorkSheet.Range("B11").Comment.Text _
     Text:="trevorc:" & Chr(10) & "test"

End Sub

Use it as

   AddComments Current_Worksheet

or

Public Sub AddComments(ARange As Excel.Range)

   ARange.AddComment
   ARange.Comment.Visible = False
   ARange.Comment.Text _
     Text:="trevorc:" & Chr(10) & "test"

End Sub

Use it as

   AddComments Current_Worksheet.Range("B11")


I would assume the second method is what you need.


mfG
--> stefan <--
0
Stefan
2/1/2010 9:21:39 AM
It is quite easy to perform operations in Excel, and control the entire 
process from Access. 

Make sure you set a reference to Excel, and then run this code in an Access 
module:

Option Compare Database
Option Explicit ' Use this to make sure your variables are defined
' One way to be able to use these objects throughout the Module is to 
Declare them here, and not in a Sub

Private objExcel As Excel.Application
Private xlWB As Excel.Workbook
Private xlWS As Excel.Worksheet
 
Sub Rep()
Dim strFile As String
strFile = "C:\MyExcelWorkbook.xls"

' Of course, this is just an example; put the actual path to your actual 
file here…
' Opens Excel and makes it Visible
Set objExcel = New Excel.Application
objExcel.Visible = True

' Opens up a Workbook
Set xlWB = objExcel.Workbooks.Open(strFile)

' Sets the Workseet to the last active sheet - Better to use the commented 
version and use the name of the sheet.
Set xlWS = xlWB.ActiveSheet

' Set xlWS = xlWB("Sheet1")
With xlWS ' You are now working with the Named file and the named worksheet
' Your Excel code begins here…you can record a macro and make the process 
super easy!!
End With

' Close and Cleanup
xlWB.SaveAs xlSaveFile
xlWB.Close
xlapp.Quit
Set xlapp = Nothing

End Sub

-- 
Ryan---
If this information was helpful, please indicate this by clicking ''Yes''.


"Stefan Hoffmann" wrote:

> hi Trevor,
> 
> On 01.02.2010 10:05, trevorC via AccessMonster.com wrote:
> > THE code here works if left here but not in it's own sub procedure.- 'CAll
> > Add_Comments'
> >
> >      Current_Worksheet.Range("B11").AddComment
> >      Current_Worksheet.Range("B11").Comment.Visible = False
> >      Current_Worksheet.Range("B11").Comment.Text Text:="trevorc:"&  Chr(10)&
> > "test"
> >
> > I was hoping to then add code to this sub procedure.
> It works if you define it correctly:
> 
> Public Sub AddComments(AWorkSheet As Excel.Worksheet)
> 
>    AWorkSheet.Range("B11").AddComment
>    AWorkSheet.Range("B11").Comment.Visible = False
>    AWorkSheet.Range("B11").Comment.Text _
>      Text:="trevorc:" & Chr(10) & "test"
> 
> End Sub
> 
> Use it as
> 
>    AddComments Current_Worksheet
> 
> or
> 
> Public Sub AddComments(ARange As Excel.Range)
> 
>    ARange.AddComment
>    ARange.Comment.Visible = False
>    ARange.Comment.Text _
>      Text:="trevorc:" & Chr(10) & "test"
> 
> End Sub
> 
> Use it as
> 
>    AddComments Current_Worksheet.Range("B11")
> 
> 
> I would assume the second method is what you need.
> 
> 
> mfG
> --> stefan <--
> .
> 
0
Utf
2/1/2010 5:15:02 PM
Hi,
I don't have a problem with interfacing with excel, theres only 2 things I
can't do as yet (turn off print text box(I can create it but not turn it off
when printing), create code and save it to a macro in excel, I can create the
macro but not assign the code to it.),but thats a different day.

What  I am trying to do is re-use common code that i need in a loop, I don't
want to have 50 copies of this in my app, so I thought to use a sub procedure
and call it were required. This works fine in access for other subs I have
created but not if I am also interacting with excel at the same time. I have
tried adding the references to excel that are in the original calling
procedure as well.
All help is greatfully accepted.
regards
Trevor.

-- 
Message posted via http://www.accessmonster.com

0
trevorC
2/4/2010 10:22:40 PM
Reply:

Similar Artilces:

access 97 backend with 2000, 2002, and 2003 front ends
Is this possible to have the 97 users with 97 front end, 2000 users with 2000 front end, 2002 users with 2002 front end, and 2003 users with 2003 front end all linked up to an access 97 backend? We are currently planning on upgrading workstations with either 2000, 2002, 2003. the criteria for the specific version will depend on the IT department. I would like to know if we have several different office versions will it work to have access 97 as a back end?? thanks in advance jung That should work fine. Same rules as usual: make sure everyone has their own copy of the front end, preferably ...

Excel 2007
When I select cells to copy as a picture in Excel 2007, the resolution is terrible. Text and objects with shadow's are very blotchy when pasting the picture. How do you change the resolution of a 'Copy Picture'? ...

Using part of a cell in a chart title
I have a chart which should get a title. However, this should be partly be used from a cell e.g. "counted with 5%" 5% should be taken from the cell and used in the title. Is this possible? Hi, Yes it's possible but all of the chart title needs to be in the cell. So you may need to use a helper cell and concatenate text and value. http://www.andypope.info/tips/tip001.htm Cheers Andy -- Andy Pope, Microsoft MVP - Excel http://www.andypope.info "Nicole" <Nicole@discussions.microsoft.com> wrote in message news:5CB7A971-AA7F-4C34-BB42-7DC283AA2958@micro...

Input Excel 'Password to Open' through control in access form
Hi All, We know,Excel has prompt password to open it files. Is it possible to create a code that can supplies the excel prompt password?.So that when we open the excel file through our access control in a form, the excel files can be opened automatically.But when the excel files opened from its default icon,it will prompt a password first. ...

Using expression builder object
Hi, I'm developing a wizzard in Access which builds import templates for various data sources to a fixed set of tables. In step 3 the users must be able to build an expression ; for instance Left([Fieldx],20) . Now I would like to have a command button on my form which calls the Access expression builder to allow the users to use this to build the expression. This expression will then be stored in a text box linked to the templates table. Anybody know how to call and use this object from VBA code? -- Kind regards Noëlla DoCmd.RunCommand acCmdInvokeBuilder I th...

Excel not Access
I have designed an Access database that holds records relating to my stores audit results going back for about 5 years plus a load more information relating to these stores. This was used to produe a pack once a month, however a change in senior management means that I have got to shelve this and prodce a similar pack in Excel. The idea would be that the user could select a month or a 12 mnth date range that would produce data that could then be used to populate a number of excel templates that have been designed. Having not used excel for years I would be grateful for any suggestion...

Administrative Groups
I have 2 Administrative groups with a Exchange 2003 Server in each group. One group is on the other side of campus and is controlled by their Exchange Server Tech. I have delegated control of my server to myself. There are also users from the other server that do not belong in my server and would like to remove them. The problem is, that when I go to remove them it will not , because the user or group is inherited from the organization. How can I remove them from my server and yet not remove them from their server? It sounds like that if I remove them from the orgainization that they wi...

Auto-format in Microsoft Excel.
Each time i try to enter a number range, for example, 8- 10, in Excel, it constantly re-formats it to a date. If I change the formatting to "General" it turns it into a random number, usually 38209. I would like to turn off ALL auto-formatting, but that's probably asking too much. How do I disable this frustrating feature? thanks. Hi Paul When you enter "8-10" in a cell, that's not strictly a number but Excel thinks you mean a date so converts it as such. A date is a number and in your example the number 38209 represents August 10 2004 which is not a ra...

How to keep format when importing Excel into SQL.
Can anybody help me please? When I import Excel file into SQL, a field that formated as 0000000000 (custom), loosing leading zeros. I tried to change data type in SQL after importing. No luck. I appretiate any help. See if using IMEX=1 helps: http://pratchev.blogspot.com/2007/10/importing-excel-data-into-sql-server.html -- Plamen Ratchev http://www.SQLStudio.com Plamen, I tried this, but got an error: "The OLE DB provider "Microsoft.Jet.OLEDB.4.0" has not been registered." Thank you very much for looking into this. "Plamen Ratchev" wr...

Standard MFC controls behave different when showing polish characters
Hello all, I have a rather simple to describe but difficult to solve problem. Our customers want to use our ANSI MFC program to show different languages. For example Polish. When I set the font for the different controls they behave different. For example the CEdit shows the polish characters just right but the CButton with checkbox style shows glyphs instead of the special characters. Every control that is owner draw and uses for example the DrawText() function of the device context shows the characters right. I've experimented with _UNICODE for the display part and everything I could ...

How to change font size on formula bar in Excell 2007
I don't find Tools>Options>General (as suggested in other post answers) in Excel 2007. On the Office button there is an Excel Options but it doesn't provide a method of changing font size on the office but. My font is so small I can barely see it. Office button>ExcelOptions>Popular tab>in the "When creating new workbooks" section, choose font and font size -- Kind regards, Niek Otten Microsoft MVP - Excel "jimwillie" <jimwillie@discussions.microsoft.com> wrote in message news:588AAC05-0F52-404E-AA01-128E70E02D0B@microso...

Opening Excel Workbooks
I'm running into an issue where if I click on an Excel file through My Documents, it doesn't automatically bring it up. I get the toolbar but the actual spreadsheet doesn't appear on the screen. I have to click on the taskbar to get it to pop up. If I already have Excel active and I open a file through Excel, this doesn't happen. Any ideas? Here is a similar thread: http://www.excelforum.com/showthread.php?s=&threadid=237195 Rolli -- Message posted from http://www.ExcelForum.com Hi, Take a look at Tools-Options-General tab- uncheck ignore other application...

Radar chart in Access 2007 report
Can you add a Radar chart to an access 2207 report? ...

Strange Access Denied Problem with Windows 7
I got a new computer about six months ago that came with Windows Vista Home Premium 64bit. Before that I had done all of my .NET development either on an XP Pro VM or my former XP Pro computer at home. Shortly after getting my new computer at home, I also got a license for VMWare to be able to test my software on multiple platforms and configurations. I had wrote an application originally in VB.NET that was a simple backup utility. It supports mutiple backup configurations. Any given copnfiguration would define a backup which would be a list of files to backup, a list of folders to ...

Unexpected error message on closing an Excel file
Suddenly I am getting the following message when I try to close a workbook: "Your formula contains an invalid external reference to a worksheet. Verify that the path, workbook, and range name or cell reference are correct, and try again" The mysterious thing is that it does not happen consistently and that, after I click OK after the above message, I can still save the file. What might be the cause of this error message and can the "invalid reference" be tracked down using one of the utility add-ins such as J. Walkenbach's PUP? If it only happens when you close ...

help with simple maths in excel
I want to do a simple arithmatic excercise in excel for my grand daughter. It is stuff like 2+2 =4 Smart me has hit a problem at the first hurdle... I need to put 2 in one cell the + in another cell and then 2 in another = in another and then she puts the answer in the next one. So the above would have 4 cells completed and she would put the answer in the 5th one. When I use the + or = sign in a cell of its own it (excel) thinks I am doing an equation, is there a way around this? I will work on the answer like if she gets it correct or wrong how I will do that...a sound or som...

How To Copy MS Word mailing labels into Excel
I have a word doc that I want to put into Excel. I want to add some more fields to the names and addresses. Is this simple or do I have to learn how to program? Michael Rodriguez City of Grand Prairie Michael, have you tried to copy and paste the data into excel? -- Paul B Always backup your data before trying something new Please post any response to the newsgroups so others can benefit from it Feedback on answers is always appreciated! Using Excel 2000 & 97 ** remove news from my email address to reply by email ** "Michael Rodriguez" <mrodrigu@gptx.org> wrote in messa...

Filter recordset using query results
Hi all I have a form based on a query called [qry Quarterly Planning], it lists all Itineraries on the system. On this form you can filter records by specifying a Start and End Date for the [ReviewDate] and/or [Specialist]. It is a subform on a main unbound form, lets call this Subform1. Along side this I have another subform (Subform2) which displays ReviewDates that exist against an Itinerary. In other words Subform1 has a start date of an activity and if the activity lasts longer than 1 day, then the additional dates are stored in Subform2 (ItineraryDates). Currently when I...

Drag and Drop file/directory names on Tree Control.
hi, I am writing an application in which i have one Tree control. Now i want that , when user drag & drop any file/folder on tree control the file name/folder name should be add in the tree control item. User may drag and drop file from desktop or may be from directory. I just want the path of that file/foder name nothing else. so plz tell me will it be possible ... Plz Help me............. Klic..... > I am writing an application in which i have one Tree control. >Now i want that , when user drag & drop any file/folder on tree >control the file nam...

How do I use traffic lights in excel
I am wanting to use traffic lights in excel that change colour based on the result of a variance cell, ie if the result of the cell is 10 make the traffic light green, if it is 20 make the traffic light amber, if the result is 30 make the traffic light red. How do I do this? Shorty Format>Conditional Formatting>Cell Value is: Note: you can add up to 3 conditions(4 if you count default) Gord Dibben Excel MVP On Wed, 22 Dec 2004 16:35:03 -0800, Shorty <Shorty@discussions.microsoft.com> wrote: >I am wanting to use traffic lights in excel that change colour based on the &g...

Newbie Question: Using Web Services
Hello All. I've been trying to implement Infopath with CRM with no success. I've tried the example, http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnmbscrm1_2/html/mbs_crminfopathcrmintegration.asp, to no avail. I have followed the example to the letter, but find the information about publishing the Web Service to the server to be somewhat lacking. Admittedly, I am not a programmer, and I am continually running into an error in line 54: xmlDoc.LoadXml(objQuery.ExecuteQuery(objBizUser.WhoAmI(), strAllAccountsFetchXML)); Has anyone else ...

HELP! remote data not accessible msg
Hello, I have a use who is currently using a Bloomberg DDE add- in. Whenever he attempts to activate the add-in to retreive remote data, the system hangs. If I go to task manager, I then see a message stating "Remote data not accessible. To access this data Excel needs to open another program.... I have searched the knowledge base and didn't find much help. Does anyone have any ideas? I am desperate!!!! We are currently using Excel 2003 in XP Professional. TIA, Ramissah ...

McAfee 8.5.0i on access scan slows down MS Dynamics CRM web client
Our organization's McAfee 8.50i slows down MS Dynamics CRM v4 - on premise web client considerabley when loading forms and data. Besides completely disabling McAfee, does anyone know how to configure McAfee (or configure CRM) to ignore CRM related form and data loads. When disabling the oncaccess scan, or when disabling the scriptcan - it improves lookups from 8-9 seconds to 4-5 seconds. However, the organizatin policy is to have these enabled. What to do? We have the same behavior, and went we reported to Microsoft says that no solution has, then we buy and install Microsoft Securi...

[b]Can I download Excel data to a MS Access database?[/b]
I've built an Excel 2002 form that I want our internal customers to access from our intranet, and use. Once completed, they will send it to us as an e-mail attachment. I'd like to be able to open it, and somehow download the data from the form into an MS Access 2002 database I've built (so that we don't have to rekey it into the database). Is this possible or even feasible? Any and all help is appreciated. Thanks. :D --------- Message sent via www.excelforums.com Hi in Access check 'File - Import External data' -- Regards Frank Kabel Frankfurt, Germany "...

Using Visio HTML output within frames
Hi, I want to include visio HTML output in a frame of another html file. Unfortunately it is not working. I understood the problem is in vml_*.htm files. It is due to, the target arrtibute(pointing to _parent) in v:shapetype tag and href attribute (pointing to #) in v:shape tag. These attributes should point to "_top" and "<target-html-file>#" respectively inorder to work. I want to change these options while saving .vsd as web page? I would appreciate if you can help me in this regard. <v:shapetype id="VISSHAPE" target="_parent" coor...