2010-12-22 64 views
0

我有一个基于条件格式化单元格的宏。 这里是代码:从c#打开文件时Excel宏没有正确执行#

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) 

Set MyPlage = Sheets("Report").Range("E13:E1500") 
For Each Cell In MyPlage 
    If Cell.Value = "L" Then 
     Cell.Borders.ColorIndex = 1 
     Cell.Font.ColorIndex = 3 
    ElseIf Cell.Value = "K" Then 
     Cell.Borders.ColorIndex = 1 
     Cell.Font.ColorIndex = 44 
    ElseIf Cell.Value = "J" Then 
     Cell.Borders.ColorIndex = 1 
     Cell.Font.ColorIndex = 10 
    ElseIf Cell.Value = "ü" Then 
     Cell.Borders.ColorIndex = 1 
    ElseIf Cell.Value = "" And Cell.Offset(0, 1).Value <> "" Then 
     Cell.Borders.ColorIndex = 1 
    Else 
    Cell.Borders.ColorIndex = 2 
End If 

Next 

该宏在保存工作簿之前执行。 它从excel中完美地工作。

我的问题是,我有一个C#应用程序,打开这个excel文件,并用数据更新它。

当我保存文件(从代码)并打开文件(从桌面或任何地方)时,我看到宏已经运行,但颜色(格式)对某些单元格不正确。

例如,如果单元格值为“OK”,则格式化单元格的颜色应为“红色”。 当我从Excel中保存工作簿时,所有带有“OK”值的单元格都是红色的。大!但是,当我运行我的应用程序打开文件,进行更改并保存它时,一些“OK”单元格是“红色”(太棒了!),但其他是“绿色”(坏!)。

有没有人有想法?

谢谢

回答

0

一个建议,可能是值得一试:将VBA代码到一个新的程序,例如

Public Sub UpdateFormats 
    Set MyPlage = Sheets("Report").Range("E13:E1500") 
    For Each Cell In MyPlage 
    .... 
End Sub 

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) 
    call UpdateFormats 
End Sub 

然后在保存和关闭工作表之前从C#明确调用例程。您也可以从BeforeSave处理程序中调用相同的例程。

这可能允许您在纸张仍然打开的同时观察正在调用的例程 - 这是在纸张关闭后打开纸张的改进。

0

不,我不能从代码调用宏,因为应用程序是将MPP任务报告给XLS文件的应用程序,并且XLS文件格式可以根据使用它的人员进行更改。有时候XLS文件没有宏。

我找到了我的答案。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) 

Set MyPlage = Sheets("Report").Range("E13:E1500") 
For Each Cell In MyPlage 
    If Cell.Value = "L" Then 
     Cell.Borders.ColorIndex = 1 
     Cell.Font.ColorIndex = 3 
    ElseIf Cell.Value = "K" Then 
     Cell.Borders.ColorIndex = 1 
     Cell.Font.ColorIndex = 44 
    ElseIf Cell.Value = "J" Then 
     Cell.Borders.ColorIndex = 1 
     Cell.Font.ColorIndex = 10 
    ElseIf Cell.Value = "ü" Then 
     Cell.Borders.ColorIndex = 1 
     Cell.Font.ColorIndex = 1 
    ElseIf Cell.Value = "" And Cell.Offset(0, 1).Value <> "" Then 
     Cell.Borders.ColorIndex = 1 
     Cell.Font.ColorIndex = 1 
    Else 
    Cell.Borders.ColorIndex = 2 
End If 

Next 

末次 有了这个代码,格式改变甚至黑色字体为我没有specifiy值每一次。这就是为什么当一个值改变时,之前有绿色字体的单元格保留了grenn,因为这个单元格应该是黑色字体。