0

我使用 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# 中执行此操作的唯一原因是我无法使其工作。那里的任何帮助都会同样有帮助。

4

1 回答 1

1
var workbookMainModule = wkBk.VBProject.VBComponents.Item("ThisWorkbook");
                workbookMainModule.CodeModule.AddFromString(sCode);
于 2012-08-22T08:38:53.487 回答