繁体   English   中英

从C#打开文件时Excel宏无法正确执行

[英]Excel macro doesn't execute correctly when opening file from c#

我有一个宏,可以根据条件格式化单元格。 这是代码:

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保存工作簿时,所有具有“确定”值的单元格均为红色。 大!

但是,当我运行打开文件,进行更改并保存的应用程序时,某些“确定”单元格为“红色”(很好!),而另一些为“绿色”(不好!)。

有人有主意吗?

谢谢

一个可能值得尝试的建议:将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处理程序中调用同一例程。

这可能使您可以观察到仍在打开床单时调用的例程-与在关闭床单后必须打开床单相比有所改善。

不,我无法从代码中调用宏,因为该应用程序是将MPP任务报告给XLS文件的应用程序,并且XLS文件格式可以根据使用它的人而改变。 Somethimes 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

End Sub使用此代码,即使对于我未指定值的黑色字体,格式每次也会更改。 这就是为什么当值更改时,对于应该具有黑色字体的单元格,之前带有绿色字体的单元格保持为grenn之后的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM