How to automate Excel using MFC and worksheet functions

 
View products that this article applies to.
Article ID : 178781
Last Review : March 8, 2005
Revision : 4.0
This article was previously published under Q178781
On This Page
 
SUMMARY
 
MORE INFORMATION
 
Steps to Create the Project
 
REFERENCES
SUMMARY
This article describes how to automate Microsoft Excel 97, Microsoft Excel 2000, Microsoft Excel 2002, or Microsoft Excel 2003 by using the Microsoft Foundation Class (MFC) library, version 4.2 (installed with Microsoft Visual C++ versions 5.0 and 6.0). Specifically, this article illustrates how to use worksheet functions provided by an add-in such as the Analysis ToolPak (ATP) and how to use the worksheet formula functions that are built-in to Microsoft Excel.
 Back to the top
 
MORE INFORMATION
You can copy the code in this article to the message handler function of an event defined in an MFC .cpp file. However, the purpose of the code is to illustrate the process of using the IDispatch interfaces and member functions defined in the Excel8.olb for Excel 97, in Excel9.olb for Excel 2000, and in Excel.exe for the Excel 2002 and Excel 2003 type library. The primary benefit comes from reading and understanding the code in the example, so that you can modify the example or write code from scratch to automate a worksheet function in Microsoft Excel using MFC.
 Back to the top
 
Steps to Create the Project
1. Follow steps 1 through 12 in the following Microsoft Knowledge Base article to create a sample project that uses the IDispatch interfaces and member functions defined in the Excel8.olb, or Excel9.olb, or Excel.exe for Excel 2002 and Excel 2003 type library:
178749 (http://support.microsoft.com/kb/178749/EN-US/) How To Create an Automation Project Using MFC and a Type Library 
2. At the top of the AutoProjectDlg.cpp, add the following line:      #include "excel8.h"
                                       
If you are automating Excel 2000, include excel9.h. If you are automating Excel 2002 or Excel 2003, include excel.h
 
 
3. Add the following code to CAutoProjectDlg::OnRun() in the AutoProjectDLG.cpp file: Sample Code:       try
      {
      _Application app;     // app is an _Application object.
      _Workbook book;       // More object declarations.
      _Worksheet sheet;
      Workbooks books;
      Worksheets sheets;
 
      Range range;          // Used for Microsoft Excel 97 components.
      LPDISPATCH lpDisp;    // Often reused variable.
 
      // Common OLE variants. Easy variants to use for calling arguments.
      COleVariant
        covTrue((short)TRUE),
        covFalse((short)FALSE),
        covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
 
      // Start Microsoft Excel, get _Application object,
      // and attach to app object.
      if(!app.CreateDispatch("Excel.Application"))
       {
        AfxMessageBox("Couldn't CreateDispatch() for Excel");
        return;
       }
 
 
      // Set visible.
      app.SetVisible(TRUE);
 
      // Register the Analysis ToolPak.
      CString sAppPath;
 
      sAppPath.Format ("%s//Analysis//Analys32.xll", app.GetLibraryPath());
 
      if(!app.RegisterXLL(sAppPath))
        AfxMessageBox("Didn't register the Analys32.xll");
 
      // Get the Workbooks collection.
      lpDisp = app.GetWorkbooks();     // Get an IDispatch pointer.
      ASSERT(lpDisp);
      books.AttachDispatch(lpDisp);    // Attach the IDispatch pointer
                                       // to the books object.
 
      // Open a new workbook and attach that IDispatch pointer to the
      // Workbook object.
      lpDisp = books.Add( covOptional );
      ASSERT(lpDisp);
      book.AttachDispatch( lpDisp );
 
         // To open an existing workbook, you need to provide all
         // arguments for the Open member function. In the case of
         // Excel 2002 you must provide 16 arguments.
         // However in Excel 2003 you must provide 15 arguments.
         // The code below opens a workbook and adds it to the Workbook's
         // Collection object. It shows 13 arguments, required for Excel
         // 2000.
         // You need to modify the path and file name for your own
         // workbook.
 
      //
      // lpDisp = books.Open("C://Test",     // Test.xls is a workbook.
      // covOptional, covOptional, covOptional, covOptional, covOptional,
      // covOptional, covOptional, covOptional, covOptional, covOptional,
      // covOptional, covOptional );   // Return Workbook's IDispatch
      // pointer.
 
      // Get the Sheets collection and attach the IDispatch pointer to your
      // sheets object.
      lpDisp = book.GetSheets();
      ASSERT(lpDisp);
      sheets.AttachDispatch(lpDisp);
 
      // Get sheet #1 and attach the IDispatch pointer to your sheet
      // object.
      lpDisp = sheets.GetItem( COleVariant((short)(1)) );
                                        //GetItem(const VARIANT &index)
      ASSERT(lpDisp);
      sheet.AttachDispatch(lpDisp);
 
      // Fill range A1 with "1/25/98", the settlement date.
      lpDisp = sheet.GetRange(COleVariant("A1"), COleVariant("A1"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetValue(COleVariant("1/25/98")); // Excel 97 & Excel 2000
 
range.SetValue2(COleVariant("1/25/98")); // Excel 2002 and Excel 2003
 
 
      // Fill range A2 with "11/15/99", the maturity date.
      lpDisp = sheet.GetRange(COleVariant("A2"), COleVariant("A2"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetValue(COleVariant("11/15/99")); // Excel 97 & Excel 2000
 
range.SetValue2(COleVariant("11/15/99")); // Excel 2002 and Excel 2003
 
 
      // Fill range A3 with "2", the frequency for semi-annual interest
      // payments.
      lpDisp = sheet.GetRange(COleVariant("A3"), COleVariant("A3"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetValue(COleVariant("2")); // Excel 97 & Excel 2000
 
range.SetValue2(COleVariant("2")); // Excel 2002 and Excel 2003
 
      // Fill range A4 with 1, the basis (actual/actual).
      lpDisp = sheet.GetRange(COleVariant("A4"), COleVariant("A4"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetValue(COleVariant("1")); // Excel 97 & Excel 2000
 
range.SetValue2(COleVariant("1")); // Excel 2002 and Excel 2003
 
      // Fill range C1 with the formula "=COUPNCD(A1, A2, A3, A4)" and
      // format the cell with a Date type of the Number format.
      lpDisp = sheet.GetRange(COleVariant("C1"), COleVariant("C1"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetNumberFormat(COleVariant("mm/dd/yy"));
      range.SetFormula(COleVariant("=COUPNCD(A1, A2, A3, A4)"));
 
      /* This is an alternative that works without placing variables on
      // the worksheet.
      // The values are arguments contained in the SetFormula() call.
      // range.SetFormula(COleVariant(
                       "=COUPNCD(/"09/15/96/",/"11/15/99/",2,1)"));
      */
 
      // *** The example in this block uses a built-in Microsoft Excel
      // function.
 
      // You do not have to register any add-in to use the built-in
 
      // Microsoft Excel worksheet functions.
      lpDisp = sheet.GetRange(COleVariant("C3"), COleVariant("C3"));
      ASSERT(lpDisp);
      range.AttachDispatch(lpDisp);
      range.SetFormula(COleVariant("=SUM(A3, A4)"));
      // or use:
      // range.SetFormula(COleVariant("=SUM(2,1)"));
 
      // *** End of example for built-in function usage.
 
      // Release dispatch pointers.
      range.ReleaseDispatch();
      sheet.ReleaseDispatch();
      // This is not really necessary because
      // the default second parameter of AttachDispatch releases
      // when the current scope is lost.
 
      } // End of processing.
 
        catch(COleException *e)
      {
        char buf[1024];     // For the Try...Catch error message.
        sprintf(buf, "COleException. SCODE: %08lx.", (long)e->m_sc);
        ::MessageBox(NULL, buf, "COleException", MB_SETFOREGROUND | MB_OK);
      }
 
      catch(COleDispatchException *e)
      {
        char buf[1024];     // For the Try...Catch error message.
        sprintf(buf,
               "COleDispatchException. SCODE: %08lx, Description: /"%s/".",
               (long)e->m_wCode,(LPSTR)e->m_strDescription.GetBuffer(512));
        ::MessageBox(NULL, buf, "COleDispatchException",
                           MB_SETFOREGROUND | MB_OK);
      }
 
      catch(...)
      {
        ::MessageBox(NULL, "General Exception caught.", "Catch-All",
                           MB_SETFOREGROUND | MB_OK);
      }
                                       
 
 
 Back to the top
 
REFERENCES
For additional information about the Automation of Office applications, click the article number below to view the article in the Microsoft Knowledge Base:
222101 (http://support.microsoft.com/kb/222101/EN-US/) How To: Find and Use Office Object Model Documentation
 
### 回答1: Power Automate Excel是微软的一款自动化工具,可以帮助用户自动化Excel中的各种操作,如数据导入、数据处理、数据分析等。用户可以通过Power Automate Excel来创建自动化流程,从而提高工作效率和准确性。同时,Power Automate Excel还支持与其他应用程序的集成,如Outlook、SharePoint等,使得用户可以更加方便地进行数据交互和协作。 ### 回答2: Power Automate Excel是微软的一种自动化工具,可以帮助用户自动将Excel文件中的数据导入到其他应用程序中。Power Automate Excel使用一种称为“Power Query”的技术,该技术可以自动连接数据源并轻松转换数据。 使用Power Automate Excel,您可以自动执行各种任务,例如: 1. 将Excel数据导入到其他应用程序(如SharePoint列表、SQL Server、Dynamics 365等)中; 2.自动生成报告和分析; 3. 利用Power Query技术减少手动数据处理; 4. 使用Flow自动化Excel文件上的常见任务,例如发送电子邮件或发布到SharePoint。 使用Power Automate Excel还可以节省时间和精力,并提高生产力。用户可以使用功能强大的搜索和过滤功能,在Excel文件中快速查找大量数据。此外,使用Power Query,您还可以轻松地清理和转换数据集,以便更好地理解它们。 在总体而言,Power Automate Excel可以帮助用户更有效地管理和分析Excel数据,提高生产力和工作效率。 ### 回答3: Power Automate是微软企业级自动化工具的一部分,前身是Microsoft Flow。它允许用户自动化执行重复、繁琐的任务,从而提高工作效率和生产力。而Power Automate for Excel则通过与Excel的集成,完全可以让用户集中精力于业务价值的创造,摆脱冗长繁琐的Excel处理任务。Power Automate for Excel有以下几个主要的功能点: 1. 数据集成 通过Power Automate for Excel,用户可以通过微软认证的各种数据连接,从不同的数据源中提取并整合数据。并可在Excel中对这些数据应用各种数据处理手段,如数据清洗、整合、ETL等,从而生成用户需要的分析结果。此外,Power Automate还可以设置数据提取的自动运行,以确保数据的及时更新。 2. 自动化数据处理 Power Automate for Excel可以执行多步骤的数据转换、加工和自动化流程。例如,用户可以设置数据自动清洗,删除重复行、空值行、过期数据等等;自动计算最大值、最小值、最新日期等等。这种数据加工与流程自动化的能力无疑可以让用户节省很多时间,同时提高数据准确性,并加强业务决策的正确性和有效性。 3. 触发自动化流程 Power Automate for Excel还可以通过用户设置触发自动化流程如按日期、按事件、按条件等,使用户不仅可以更加高效地应对业务变化和需求,还可以根据事件发起工作流,以便迅速响应并满足需求。同时,不同的自动化流程可以被整合在Power Automate流程中,形成一个更为复杂和全面的系统。 4. 与其他应用自动化集成 Power Automate for Excel可以与许多不同的应用自动化集成,如Outlook、Microsoft Teams、Power BI、SharePoint、OneDrive等等。因此,用户可以方便地在这些应用中完成任务,而Power Automate for Excel可以通过流程触发来自动化集成,从而实现更高效更便捷的工作方式。 总之,Power Automate for Excel是一种功能强大,使用方便的数据整合、数据处理、数据分析和工作流程自动化工具。它不仅可以提升用户的工作效率,还可以加速业务决策的过程,满足企业的需求和要求。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值