2012-06-27 83 views
0

我使用C#開發了一個Windows服務,該服務處理文件夾中的多個Excel文件以添加條件格式,調整頁面佈局和打印設置並添加宏以調整頁面休息。我遇到的問題是試圖將一行代碼添加到Workbook_Open例程中的ThisWorkbook對象,以便在打開文件時自動運行宏。我使用的宏添加到Module 1的代碼如下:如何將宏添加到ThisWorkbook Workbook_打開使用C#Excel Interop

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
var workbookMainModule = wkBk.VBProject.VBComponents.Item("ThisWorkbook"); 
       workbookMainModule.CodeModule.AddFromString(sCode); 
+3

一些解釋可能在這裏很有幫助 –

相關問題