Visual Studio Tools for Office: Using C# with Excel, Word, Outlook, and InfoPath【11】

User-defined functions programmed
functions in Excel can be used to create formulas in Excel user-defined. Developers must create a special type of DLL called XLL. Excel also allows you to write custom functions can be used in Excel formulas in VBA. Unfortunately, Excel does not support or recommend the use of managed code written in XLL.

Build user-defined function to provide management automation add-ons
Fortunately, creating a need to create a user-defined function XLL there is an easier way. Excel 2003 supports custom automation technology called add-ons, you can easily create in C # or Visual Basic.

First, start Visual Studio and create a new C # Class Library project. Name the project AutomationAddin. In the Class1.cs file that you created for your new project, enter the code shown in Listing 3-1. This code defines a class called MyFunctions, which implements a function called the MultiplyNTimes. We will use this function as a custom formula. Our class also implements RegisterFunction and UnregisterFunction, which are attributed to the properties and ComUnregisterFunction ComRegisterFunction property. When COM assemblies registered for COM Interop, RegisterFunction will be called. When the compilation is not registered COM interop, UnregisterFunction will be called. These features placed a necessary key in the registry that allows Excel to know of such automation can be used as add-ons.

3-1 multiplication function list is referred to as a C # class MyFunction, it exposes a user-defined

Copy the code
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace AutomationAddin
{
  [ClassInterface(ClassInterfaceType.AutoDual)]
  public class MyFunctions
  {
    public MyFunctions()
    {
    }

    public double MultiplyNTimes(double number1, double number2, double timesToMultiply)
    {
      double result = number1;
      for (double i = 0; i < timesToMultiply; i++)
      {
        result = result * number2;
      }
      return result;
    }

    [ComRegisterFunctionAttribute]
    public static void RegisterFunction(Type type)
    {
      Registry.ClassesRoot.CreateSubKey( GetSubKeyName(type));
    }

    [ComUnregisterFunctionAttribute]
    public static void UnregisterFunction(Type type)
    {
      Registry.ClassesRoot.DeleteSubKey(GetSubKeyName(type),false);
    }

    private static string GetSubKeyName(Type type)
    {
      System.Text.StringBuilder s = new System.Text.StringBuilder();
      s.Append(@"CLSID\{");
      s.Append(type.GUID.ToString().ToUpper());
      s.Append(@"}\Programmable");
      return s.ToString();
    }
  }
}
Copy the code

Use this code to write, you need to modify the program to automatically register the class when building COM interop. First, to display the attributes of the item by double-clicking the "Properties" node under the "Solution Explorer" in the project node. In the event of property design, click the "Build" tab, then select the "Register COM Interop" box, shown in Figure 3-7. Then select Build Solution from the Build menu to build the library project. Your action will result in your class library project is building automation as well as add-ins registered in the registry. Excel can now see your C # class and use it.

Figure 3-7 is provided to register the build options COM interoperability

Use Management in Excel Automation Add
Start Excel and select Add-ons from the Tools menu to display the Add-Ins dialog box. In the Add-Ins dialog box, click the button automation. You can find the class that you create by looking AutomationAddin.MyFunctions in the automation server list, shown in Figure 3-8.


Figure 3-8 Select "AutomationAddin.MyFunction" from "Automation Server" dialog

Click OK in this dialog box, you have AutomationAddin.MyFunctions class added to the list of installed items Loading automation, shown in Figure 3-9.


Figure 3-9 AutomationAddin.MyFunction already installed 

Now, try to use the function MultiplyNTimes in Excel formulas. Start by creating a simple spreadsheet, which contains a number, the second number is multiplied by the first digit, the third digit number for the second digit of the first number is multiplied. The spreadsheet shown in Figure 3-10.


Figure 3-10 a simple spreadsheet to test custom formulas

Click on an empty cell numbers under workbook, and then click the Insert Function button in the formula bar (with buttons "fx" label). Can be formulated from the dialog, drop-down "or select the category" drop-down box, and select AutomationAddin.MyFunction. Then click "Multiplyntimes" function, shown in Figure 3-11.


Figure 3-11 Select "multiplier" from the "Insert Function" box

单击“确定”按钮后,Excel弹出对话框,帮助从电子表格中的单元格中选择功能参数,如图3-12所示。


图3-12  设置函数参数

从相应的单元格中选择功能参数后,单击“确定”创建最终的电子表格,如图3-13所示,单元格C5中的自定义公式。


图3-13 最终的电子表格

一些其他用户定义的函数
您可以尝试Excel公式中可以使用的其他功能。 例如,清单3-2显示了可以添加到MyFunctions类的其他几个函数。 要使用清单3-2,您必须添加对Excel 11.0对象库的引用,并将代码使用Excel = Microsoft.Off-ice.Interop.Excel添加到类文件的顶部。 请注意,当您将参数声明为对象时,Excel会传递一个Range对象。 还要注意AddNumbers函数支持可选参数。 当省略一个参数时,System.Type.Missing作为参数的值传递。

清单3-2  可以添加到MyFunctions类的其他用户定义的函数

Copy the code
public string GetStars(double number)
{
  System.Text.StringBuilder s =  new System.Text.StringBuilder();
  s.Append('*', number);
  return s.ToString();
}

public double AddNumbers(double number1,  [Optional] object number2, [Optional] object number3)
{
  double result = number1;

  if (number2 != System.Type.Missing)
  {
    Excel.Range r2 = number2 as Excel.Range;
    double d2 = Convert.ToDouble(r2.Value2);
    result += d2;
  }

  if (number3 != System.Type.Missing)
  {
    Excel.Range r3 = number3 as Excel.Range;
    double d3 = Convert.ToDouble(r3.Value2);
    result += d3;
  }

  return result;
}

public double CalculateArea(object range)
{
  Excel.Range r = range as Excel.Range;
  return Convert.ToDouble(r.Width) +  Convert.ToDouble(r.Height);
}

public double NumberOfCells(object range)
{
  Excel.Range r = range as Excel.Range;
  return r.Cells.Count;
}

public string ToUpperCase(string input)
{
  return input.ToUpper();
}
Copy the code

在管理型自动化加载项中调试用户定义的函数
您可以通过将Excel设置为您的类库项目在调试时启动的程序来调试作为自动化加载项的C#类库项目。 通过双击“解决方案资源管理器”中项目节点下的“属性”节点来显示项目的属性。 在出现的属性设计器中,单击“调试”选项卡,在“启动外部程序”文本框中,键入Excel.exe的完整路径,如图3-14所示。 现在,在您的一个用户功能上设置断点,按F5,然后使用电子表格中的功能。 调试器将停止执行断点设置的用户函数。


图3-14 设置调试选项以启动Excel

部署管理型自动化加载项
要部署自动化加载项,请在解决方案资源管理器中右键单击解决方案,然后从“添加”菜单中选择“新建项目”。 从“添加新项目”对话框中,在“项目类型”树中选择“从其他项目类型\安装和部署”中的“安装项目”。

右键单击解决方案资源管理器中添加的安装项目,然后从添加菜单中选择项目输出。 从“添加项目输出组”对话框中,选择“AutomationAddin”项目,选择“主要输出”,如图3-15所示。


图3-15  将Automation Addin项目的主输出添加到安装项目中

 

因为我们告诉项目注册我们用于COM互操作的托管对象,所以安装项目应该已经被正确设置,以便在安装时注册COM互操作的托管对象。 要验证此,请单击安装项目中AutomationAddin节点的主输出。 在主输出的属性窗口(我们的C#DLL)中,确保将Register设置为vsdrpCOM。

 

Excel对象模型简介
无论您选择将代码与Excel集成在一起,您最终都需要与Excel对象模型进行交流,以完成任务。 在本书中完全描述Excel对象模型是不可能的,但我们尝试让您熟悉Excel对象模型中最重要的对象,并显示这些对象上最常用的方法,属性和事件。

对象层次结构
学习Excel对象模型的第一步是获取对象模型层次结构的基本结构。 图3-16显示了Excel对象模型中最关键的对象及其层次关系。

 图3-16   Excel对象模型的基本层次结构

一个Workbook对象有一个名为Sheets的集合。 “表”集合可以包含“工作表”或“图表”类型的对象。 图表有时被称为图表,因为它涵盖了工作表将涵盖的整个区域。 您可以通过右键单击Excel工作簿左下角的工作表选项卡并选择“插入”,将工作表插入到工作簿中。 图3-17显示出现的对话框。 请注意,在Sheets集合中还有两个附加对象:MS Excel 4.0宏表和MS Excel 5.0对话框。 如果将宏表单或对话框插入到Excel工作簿中,则将其视为特殊类型的工作表,而不是与宏表或对话框对应的特殊对象模型类型。


图3-17  将各种“工作表”插入到Excel工作簿中

因为工作簿可以包含这些各种对象,Excel会从Workbook对象中提供多个集合。 Worksheets集合仅包含工作簿中的Worksheet对象。 “图表”集合仅包含工作簿中的图表。 Sheets集合是两者的混合集合。 Sheets集合将集合的成员作为类型对象返回,您必须将返回的对象转换为工作表或图表。在这本书中,当我们谈论一个可能是工作表或图表的对象时,我们将其称为工作表。

图3-18显示了一个更完整的层次结构树,其主要对象与图3-16中的对象相关联。这将开始让您了解Excel对象模型中对象的广泛层次结构,特别是当您意识到该图显示的可用对象不足一半时。以灰色显示的对象来自Microsoft.Office.Core命名空间,它与Microsoft Office 11.0 PIA(office.dll)相关联。这些对象由所有Office应用程序共享。


图3-18  Excel对象模型中某些主要对象的详细层次结构

 

图3-19显示了与Range相关联的对象层次结构,这是Excel中非常重要的一个对象,代表您要在代码中处理的单元格范围。 我们已经使用了清单3-2中的RangXe对象。


图3-19  与Excel对象模型中的Range相关联的对象的更详细层次结构

Figure 3-20 shows Shapea Shape object hierarchy and associated, on the worksheet indicates a floating cell is not something, for example, embedded buttons, graphics, annotation bubbles.


Figure 3-20 Excel object model in more detail with the object hierarchy associated Shape

Conclusion
This chapter describes the various ways to integrate the code in Excel. This chapter describes how to build automation add-in to create user-defined functions for Excel. You also learned basic Excel object model hierarchy. Chapter 4, "Using Excel event" discussed the Excel object model events. Chapter 5, "Using Excel Object" covers the Excel object model of the most important objects.

Guess you like

Origin www.cnblogs.com/qiys/p/11367302.html