On cleanuing up COM object when using Microsoft.Office.Interop.Excel

When using Microsoft.Office.Interop.Excel the COM objects that are created by the code must be released using System.Runtime.InteropServices.Marshal.ReleaseComObject().
Most of the time it's pretty clear when a new COM object is created such as:
Excel._Application excelApp = null;
Excel._Workbook wb = null;
Excel._Worksheet ws = null;
Excel.Range newRange = null;
try
// four COM objects are created below
excelApp = new Excel.Application();
wb = excelApp.Workbooks.Add();
ws = (Excel.Worksheet)wb.Worksheets.Add();
newRange = (Excel.Range)ws.Range["A1","A30"];
// do these line of cod create new COM object?
newRange.Font.Bold = true;
newRange.Borders.Color = borderColor;
finally
if (excelApp != null) Marshal.ReleaseComObject(excelApp)
if (wb != null) Marshal.ReleaseComObject(wb)
if (ws != null) Marshal.ReleaseComObject(ws)
if (newRange != null) Marshal.ReleaseComObject(newRange)
In the above code I create four COM objects in the first part that need to be released when I'm finished with them. But it's not clear if the other two lines of code create a new COM object or not.  If they do then my code needs to look more
like this:
Excel._Application excelApp = null;
Excel._Workbook wb = null;
Excel._Worksheet ws = null;
Excel.Range newRange = null;
Excel.Font fnt = null;
Excel.Borders bds = null;
try
// four COM objects are created below
excelApp = new Excel.Application();
wb = excelApp.Workbooks.Add();
ws = (Excel.Worksheet)wb.Worksheets.Add();
newRange = (Excel.Range)ws.Range["A1","A30"];
// do these line of cod create new COM object?
fnt = newRange.Font
fnt.Bold = true;
bds = new newRange.Borders;
bds.Color = borderColor;
finally
if (excelApp != null) Marshal.ReleaseComObject(excelApp)
if (wb != null) Marshal.ReleaseComObject(wb)
if (ws != null) Marshal.ReleaseComObject(ws)
if (newRange != null) Marshal.ReleaseComObject(newRange)
if (fnt != null) Marshal.ReleaseComObject(fnt)
if (bds != null) Marshal.ReleaseComObject(bds)
How can I tell if getting a property creates a new COM object or not?

Thank you for your replay but I do understand that the font object is a COM object.  What I'm trying to figure out is if a NEW object is created each time I access the font member of a Range object and if I need to call
Marshal.ReleaseComObject on the font object after using it.
Most member object of an object are a single instance and each time you access the member you simply get the pointer to that instance. For example:
using(DataTable dt = new DataTable("Some Table Name"))
PropertyCollection ep1 = dt.ExtendedProperties;
PropertyCollection ep2 = dt.ExtendedProperties;
if (Object.ReferenceEquals(ep1,ep2)) Console.WriteLine("They are the same object");
else Console.WriteLine("They are different objects");
The output will be: They are the same object
On the other hand this:
Excel._Application excelApp = new Excel.Application();
Excel._Workbook wb = excelApp.Workbooks.Add();
Excel._Worksheet ws = (Excel.Worksheet)wb.Worksheets.Add();
Excel.Range newRange = (Excel.Range)ws.Range["A1","A30"];
// do these lines of code create new COM object?
Excel.Font ef1 = newRange.Font;
Excel.Font ef2 = newRange.Font;
if (Object.ReferenceEquals(ef1,ef2)) Consloe.WriteLine("They are the same object");
else Consloe.WriteLine("They are different objects");
The output will be: They are different objects
It looks like each time I access the font member I get a new object.  I suspect that is not the case and what I am getting is two pointers to the same object and the reference counter is incremented by one.
So really the question is what happens to the font member object of the Range object when the range object is released.  I assume the font member will be released along with the Range object ever if the font object has a reference count greater then
0.
If I am correct in my assumption then I can access the font member object as much as I need to without worrying about releasing it.
I have been reading a lot about working with COM and the need to use Marshal.ReleaseComObject and there does seem to be a lot of disagreement and even confusion on the
mater about when and if COM objects need to be explicitly released.

Similar Messages

  • BPC 7.5 NW Processing Dimensions Microsoft.Office.Interop.Excell issue

    Hi
    I've tried all the downloads (service Packs, Interop Files etc) mentioned in all websites and posts to try and fix following error:
    "Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel_Application'. This Opperation failed because the Query Interface call on the COM component for the interface with ID '{000208D5-0000-0000-C000-0000000000046}' failed due to the following error: Library not registered.
    I get this only when I try to Process a dimension
    Please can anyone tell me how to fix this?
    We have installed BPC 7.5 NW
    I had Office 2010 and could process but my input schedules didn't work 100% on Office 2007 so I had to go back to 2007. And now I can't process in the Admin Client. I've uninstalled and reinstalled Office and BPC 7.5 NW SP07 a few times to try and solve this but no luck.
    Thanks
    Johan Fourie

    Hi,
    If you are using excel 2007, you need to install the redistributable primary interop assembly from the below link:
    https://websmp230.sap-ag.de/sap%28bD1lbiZjPTAwMQ==%29/bc/bsp/sno/ui_entry/entry.htm?param=69765F6D6F64653D3030312669765F7361706E6F7465735F6E756D6265723D3134363332383926
    Hope this helps.

  • I created a spreadsheet using Microsoft office 2010 Excel.  When I open the sheet using Numbers, the formatting changes.  How do I fix this?

    I created a spreadsheet using Microsoft office 2010 Excel.  When I open the sheet using Numbers, the formatting changes.  How do I fix this?

    If you plan to share or work with people who regulary use MS Excel you should not try to use this in Numbers.  You will have constant problems with how each program translates the formatting.
    If you want to use Numbers, use it exclusively.  If it is for your job use the tool your company uses.

  • Acer S7 screen flickers during videos and when using Microsoft Office Screen is white

    Had my Acer S7-392 for about 9 months and it has a problem that i've not been able to resolve. - When on some websites or watching video's (embedded into the website like on Facebook) the picture flickers and is unwatchable. If you scroll so that a little of the video is offscreen the problem stops.- Also when using microsoft office programs the screen just goes white and I can't do anything without closing the programs via task manager. I've made sure I have all the right drivers. Intel sends me to the Acer website for the drivers and I have the most up to date of those. I have phoned microsoft and they say that it is not them and even when remote accessing the machine they cannot see a problem. I'm sure its a graphics problem as other than these two irritating issues the machine works fine. Many thanks in advance for anyones help.

    Hi, I don't own an external monitor. I can take the laptop to work and use one there. If I do that and the same problem happens what does that mean? If the problem is not repeated on the monitor what does that also mean? If I can't use a monitor what else can I do? Thanks. Tom

  • How to install & use microsoft office (word,excel,powerpoint) in ipad?

    1.How to install & use microsoft office (word, excel, powerpoint) in ipad?
    2. How to delete applications in ipad once it is installed?

    Microsoft  Office won't work on iPad.
    Try Apps like:
    1. Documents To Go
    2. Quick Office Pro HD
    3. Office2 HD

  • Microsoft.Office.Interop.Excel

    Which forum should I use to ask questions about using C# & Microsoft.Office.Interop.Excel for spreadsheets?
    Rob E.

    Hello,
    I'd ask in the
    Excel for Developers forum.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book: Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C40686F746D61696C2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • File or assembly name microsoft.office.interop.excel or one of its dependen

    Hi Team,
    When i click on the manage dimension members for a dimension i am getting the following error,
    "file or assembly name microsoft.office.interop.excel or one of its dependencies was not found"
    How i can resolve this?
    Regards,
    Raj,

    Hi Raj,
    What did you do exactly to resolve this issue? Are you no longer using Office 2007 or did you reinstall it? What are the specific steps you took?
    I recently upgraded from SP02 to SP07 and now have the same problem. It was working fine prior to the upgrade.
    Thanks,
    Rob
    Edited by: Rob Delong on Feb 19, 2010 3:42 AM

  • Datamining PST Files using Microsoft.Office.Interop.Outlook

    I was wondering how to datamine a pst file beyond it's primary folders to see if an empty folder has content in a subfolder and add it to an existing psobject?
    Cheers,
    B.
    $results = New-Object System.Collections.ArrayList # Empty Array
    $null = Add-type -assembly Microsoft.Office.Interop.Outlook
    $outlook = new-object -comobject outlook.application
    $namespace = $outlook.GetNameSpace('MAPI')
    $pstpath = "d:\sample.pst"
    $namespace.AddStore($pstpath)
    $PST = $namespace.Stores | ? {$_.FilePath -eq $pstpath}
    $PSTRoot = $PST.GetRootFolder()
    $PSTName = $PST.Displayname
    Foreach ($folders in $PSTRoot.Folders) {
    $x = $folders.Name
    $y = $folders.FolderPath
    $z = $folders.Items.Count
    $Object = New-Object PSObject
    $Object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $x
    $Object | Add-Member -Name 'Path' -MemberType Noteproperty -Value $y
    $Object | Add-Member -Name 'Items' -MemberType Noteproperty -Value $z
    $results += $object
    $results | Format-Table 'Name','Path','Items' -Wrap -AutoSize | Out-Default
    $results = $NULL

    Hi B,
    If you want to test the access of the .pst file, please refer to the function below:
    function Test-PSTFile {
    param(
    [Parameter(Position=1, ValueFromPipeline=$true, Mandatory=$true)]
    $FilePath,
    [Parameter(Position=2, Mandatory=$false)]
    $ErrorLog
    process {
    #Create an instance of Outlook
    $null = Add-type -assembly Microsoft.Office.Interop.Outlook
    $olFolders = 'Microsoft.Office.Interop.Outlook.olDefaultFolders' -as [type]
    $outlook = new-object -comobject outlook.application
    #Open the MAPI profile
    $namespace = $outlook.GetNameSpace('MAPI')
    try {
    #Try to add the PST file to the profile
    $namespace.AddStore($FilePath)
    #Try to read the root folder name
    $PST = $namespace.Stores | ? {$_.FilePath -eq $FilePath}
    $PSTRoot = $PST.GetRootFolder()
    if($PSTRoot) {
    New-Object PSObject -Property @{
    FileName = $FilePath
    Valid = $True
    #Disconnect the PST
    $PSTFolder = $namespace.Folders.Item($PSTRoot.Name)
    $namespace.GetType().InvokeMember('RemoveStore',[System.Reflection.BindingFlags]::InvokeMethod,$null,$namespace,($PSTFolder))
    catch {
    #If logging is on, save the error to the log
    if($ErrorLog) {
    Add-Content -Path $ErrorLog -Value ("Ran into a problem with {0} at {1}. The error was {2}" -f $FilePath, (Get-Date).ToString(),$_.Exception.Message)
    #Output a failure record
    New-Object PSObject -Property @{
    FileName = $FilePath
    Valid = $False
    Refer to:
    How to Test Outlook (PST) Personal Folder File Access with PowerShell
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang

  • Scrreen scrolls without input when using microsoft office

    When I'm using microsoft excel or powerpoint, frequently as I am editing, the screen will scroll to a different random location. So in excel, I will suddenly be looking at a different location in the spreadsheet or in ppt, I'd be on a different slide. this happens consistently (but not reproducible) every time I use excel and ppt. And I am NOT using the mouse to intentionally scroll using double-finger etc.. There is no problem I'm using other applications. Anyone else experiencing this problem? Remedies?

    HI and Welcome to Apple Discussions.
    Try Resetting the PRAM
    Carolyn

  • Help and some explanation how to get a Microsoft.Office.Tools.Excel.Worksheet host item that extends the functionality of the current Microsoft.Office.Interop.Excel.Worksheet object

    Hello,
    I would use some help and more info about how to get host object that extends the functionality of my current Interop.Excel.Worksheet object. I read this artical: https://msdn.microsoft.com/en-us/library/ee794671.aspx where I can call this function
    GetVstoObject to get host object. But I see that here I need to pass the Globals.Factory object as second parametar. Can someone give me more details about that parameter and how to access it? I would like to get host object so I can access extension
    property, since my interop excel worksheet doesn't have it.  
    I am using Visual Studio 2013 for developing Excel addin. Using Excel 2010.
    Thanks in advance for help.
    Regards,
    Zeljka

    Hi Zeljka,
    >>I am using the Microsoft Office PIAs, so my question is how to access this automatic generated class Globals in my case?   <<
    Sorry, I am not able to understand the application you were developing exactly. From the orgnal post, you were developing an application level add-in, however based on the description above, it seems that you were building an console or Windows form application
    to automate Office application.
    If you were developing Office automation, the host item can't work for this secnario since it should run under the VSTO runtime.
    If I misunderstood, please feel free to let me know.
    Regards & Fei
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • When using Microsoft office programs it alwasy asks if i want to "Allow incoming connection"

    Ok guys i have check my firewall and I have it set to allow incoming connections yet it still always asks. How do I fix this?

    Any Front Row, Apple TV, or iDevices around?
    See 2nd to last post here...
    http://rafsoftware.com/rafsoftware/forums/viewtopic.php?f=5&t=17&start=10
    Little Snitch, stops/alerts outgoing stuff, I wonder if you tried that & set it to allways allow whatever VNC or port 5900 wants...
    http://www.obdev.at/products/littlesnitch/index.html

  • Interface not registered (Exception from HRESULT: 0x80040155) when calling Microsoft.Office.Interop.Outlook.MAPIFolder.get_Folders()

    Hi All,
    I have an Outlook COM addin written in C#. It is working without any issues on most client machines, but since of late it has started giving the above Exception for some clients running Outlook 2010.
    I understand that the issue is that the particular interface is not registered properly on those machines. I would like to know what in dll that interface is located and what could cause it to be missing? Can it be a component that had been deselected during
    the installation of Outlook? If so, what is that component? Or should the dll be manually registered (using REGSVR32)? Or will running a simple repair on Outlook work?
    Thanks!!

    Hello Thimila,
    What code do you use exactly?
    Try to run the problematic piece of code from VBA as a macro. Do you get the same error message? If so, you need to repair Outlook, it looks like windows registry entries were corrupted. 
    If you don't get such error in VBA it indicates that you didn't install/copy one of the required prerequisites to the end user PC (interop libraries, .net runtime and etc.). Make sure that all the required prerequisites are installed correctly. See Deploying
    an Office Solution for more information.

  • How to add text vertically into a Word margin with C# (using namespace: Microsoft.Office.Interop.Word)

    I need to add text vertically in a word document outside the margins.  How can I do this with Microsoft.Office.Interop.Word and C#?
    Leonard Swarczinski Software Developer Postal Center International

    Hi Leonard,
    According to your description, do you want to add text vertically into Page Header/Footer? I wrote a sample  for you.
    using Microsoft.Office.Core;
    using Microsoft.Office.Interop.Word;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace AddTextToWord
    class Program
    static void Main(string[] args)
    CreateNewDocument();
    Console.ReadLine();
    private static void CreateNewDocument()
    Object oMissing = System.Reflection.Missing.Value;
    Microsoft.Office.Interop.Word.Application oWord;
    Microsoft.Office.Interop.Word.Document oDoc;
    oWord = new Microsoft.Office.Interop.Word.Application();
    oWord.Visible = true;
    oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    String HeaderText = "Hello everyone!";
    WdParagraphAlignment wdAlign = WdParagraphAlignment.wdAlignParagraphCenter;
    AddHeader1(oWord, HeaderText, wdAlign);
    private static void AddHeader1(Application WordApp, string HeaderText, WdParagraphAlignment wdAlign)
    Object oMissing = System.Reflection.Missing.Value;
    WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
    WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
    Microsoft.Office.Interop.Word.Shape textBox = WordApp.ActiveDocument.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationVertical, 150, 10, 40, 40);
    textBox.TextFrame.TextRange.Text = HeaderText;
    WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
    If I misunderstood or anything wrong, please let me know and you can get more information from below articles.
    Office development in Visual Studio
    http://msdn.microsoft.com/en-us/office/hh133430.aspx
    Abhout: AddTextbox Method
    http://msdn.microsoft.com/en-us/library/office/aa171543(v=office.11).aspx
    How to: Programmatically Insert Text into Word Documents
    http://msdn.microsoft.com/en-us/library/vstudio/6b9478cs.aspx

  • Microsoft.Office.Interop.Word error on Windows Server 2008 R2

    Hi,
    I have Microsoft Office 2003 installed on Windows Server 2008 R2. I get a "There is insufficient memory. Save the document now." error while adding a document to the Microsoft.Office.Interop.Word.Document class as in the code below. I can see the Memory
    consumption shoots up as soon as the following lines of code is executed. Surprisingly, this same piece of code works fine on Windows Server 2008.
    Object missing = System.Reflection.Missing.Value;
    Object oFalse = false;
    Microsoft.Office.Interop.Word.Application oWord = new Application();
    Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();
    oWordDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing); //The code fails here
    oWordDoc.Close(ref oFalse, ref missing, ref missing);
    oWord.Quit(ref missing, ref missing, ref missing);
    Can someone help on this?
    Thanks,
    Tarun

    Hi,
    I suggest discussing this issue in Word or IIS forum.
    Word forum:
    http://social.technet.microsoft.com/Forums/en-us/word/threads
    IIS forum:
    http://forums.iis.net/
    Tim Quan

  • Is it possible to flag e-mails and/or right click an e-mail to mark as read/unread, etc. when using Microsoft Outlook Web Access in Firefox on a Mac?

    Is it possible to flag e-mails and/or right click an e-mail to mark as read/unread, etc. when using Microsoft Outlook Web Access in Firefox on a Mac?
    == This happened ==
    Every time Firefox opened
    == I've never been able to figure out how to do those things in Firefox.

    When you use OWA in something other than IE, you're using OWA lite and no--it is not possible to do either in OWA lite (well, new Exchange stuff makes my answer a little less emphatic but still: pretty much no). Thanks Microsoft. But this guy made it possible to mark unread/read and select all/none:
    http://david-burger.blogspot.com/2008/07/firefox-greasemonkey-outlook-web-access_19.html

Maybe you are looking for