如何使用C#Excel Interop向ThisWorkbook Workbook_Open添加宏

时间:2012-06-27 12:24:31

标签: c# excel-interop

我使用C#开发了一个Windows服务,它处理文件夹中的大量Excel文件以添加条件格式,调整页面布局和打印设置,并添加宏来调整分页符。我遇到的问题是尝试在Workbook_Open例程中向ThisWorkbook对象添加一行代码,以便在打开文件时自动运行宏。我用来将模块添加到Module1的代码如下:

    using Excel = Microsoft.Office.Interop.Excel;
    using VBIDE = Microsoft.Vbe.Interop;

    VBIDE.VBComponent oModule;
    String sCode;

    oModule = wb.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);

    sCode = 
@"Sub FixPageBreaks()
    On Error GoTo ErrMsg

    Dim wb As Workbook
    Set wb = ActiveWorkbook

    Dim sheet As Worksheet
    Set sheet = wb.Worksheets(1)

    Dim vBreaks As VPageBreaks
    Set vBreaks = sheet.VPageBreaks

    If vBreaks.Count > 0 Then
        Dim lastCol As Integer
        lastCol = ActiveSheet.Cells.Find(What:=""*"", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False, SearchFormat:=False).Column

        Dim lCount As Integer
        lCount = 1

        Dim brkCol As Integer

        Dim brkRng As Range

        Dim iReply As VbMsgBoxResult

        Do
            If vBreaks(lCount).Location.Column = lastCol Then
                brkCol = vBreaks(lCount).Location.Column + 1
            Else
                brkCol = vBreaks(lCount).Location.Column - 1
            End If

            Set brkRng = Range(sheet.Cells(1, brkCol), sheet.Cells(1, brkCol))

            If brkCol Mod 2 = 1 And lastCol > brkCol Then
                Set vBreaks(lCount).Location = brkRng
            ElseIf brkCol Mod 2 = 1 Then
                vBreaks(lCount).DragOff Direction:=xlToRight, RegionIndex:=1
            End If

            lCount = lCount + 1
        Loop While lCount <= vBreaks.Count

        sheet.PrintPreview
    End If
Exit Sub
ErrMsg:
    MsgBox Err.Description
End Sub";

    oModule.CodeModule.AddFromString(sCode);

在第

wb.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);

wb 是代码中先前实例化的工作簿对象。这一切都有效,但是,我似乎找不到关于vbext_ComponentType枚举的大量文档来确定哪一个(如果有的话)代表工作簿中的ThisWorkbook对象以及如何向其添加代码。我也很高兴找到与Excel文档中的宏一样的分页符的C#代码。我在C#中没有像其他处理那样做的唯一原因是我无法使其工作。任何帮助都会有同样的帮助。

1 个答案:

答案 0 :(得分:1)

var workbookMainModule = wkBk.VBProject.VBComponents.Item("ThisWorkbook");
                workbookMainModule.CodeModule.AddFromString(sCode);