VBA:使Excel条件格式在Outlook中工作

时间:2015-07-31 00:37:42

标签: vba excel-vba outlook-vba excel

我有一个Outlook VBA脚本正在进行一些电子邮件解析并将结果放入脚本创建的新Excel文档中。

VBA展望部分存在问题:

sub test
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0
    Set oXLwb = oXLApp.Workbooks.Add
    Set oXLws = oXLwb.Sheets("Sheet1")

    ' lots of stuff here that parses emails and puts them in the spreadsheet

    Call formatRN(oXLws)
end sub

Sub formatRN(xlsheet As Object)

    ' row and column sizes
    xlsheet.Cells.RowHeight = 15
    xlsheet.Columns("A:A").ColumnWidth = 50
    xlsheet.Columns("B:B").EntireColumn.AutoFit
    xlsheet.Columns("C:C").EntireColumn.AutoFit
    xlsheet.Columns("D:D").ColumnWidth = 50
    xlsheet.Columns("E:E").ColumnWidth = 50
    xlsheet.Columns("F:F").ColumnWidth = 50
    xlsheet.Columns("G:G").ColumnWidth = 50
    xlsheet.Columns("H:H").ColumnWidth = 50
    xlsheet.Columns("I:I").ColumnWidth = 50


    ' conditional format for empty cells
    xlsheet.Columns("A:I").Select
    xlsheet.Columns("A:I").FormatConditions.Add Type:=xlExpression, Formula1:="=LEN(TRIM(A1))=0"
    xlsheet.Columns("A:I").FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With xlsheet.Columns("A:I").FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = -0.499984740745262
    End With
    xlsheet.Columns("A:I").FormatConditions(1).StopIfTrue = False


End Sub

该行: xlsheet.Columns(&#34; A:I&#34;)。FormatConditions.Add类型:= xlExpression,Formula1:=&#34; = LEN(TRIM(A1))= 0&#34;

给我错误:&#34;无效的电话或参数&#34;

以下代码在Excel中运行FINE。我不确定问题是什么:

sub test()
    Dim xlsheet As Worksheet
    Set xlsheet = ActiveSheet

    xlsheet.Columns("A:I").Select
    xlsheet.Columns("A:I").FormatConditions.Add Type:=xlExpression, Formula1:="=LEN(TRIM(A1))=0"
    xlsheet.Columns("A:I").FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With xlsheet.Columns("A:I").FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = -0.499984740745262
    End With
    xlsheet.Columns("A:I").FormatConditions(1).StopIfTrue = False
end sub

由于我在脚本中制作excel表格,因此我无法在excel表格中预先存在此vba代码,我宁愿不必在excel中添加单独的全局级别vba代码此代码的最终用户的计算机。

任何提示都会很棒,谢谢!

1 个答案:

答案 0 :(得分:3)

如果您正在使用后期绑定的Excel(没有明确引用Microsoft Excel对象模型),那么您正在执行此操作,那么作为该模型一部分的枚举常量,例如xlExpression将被解释为具有零值的未声明变量。其值应为2

将此放在代码顶部,以警告您将来遇到的所有问题:

Option Explicit

然后,将变量声明为:

Const xlExpression As Long = 2

Excel中使用时,Excel中的代码不依赖于Excel对象模型和相关枚举常量的外部引用,这就是代码在Excel中工作的原因,但从其他应用程序调用时似乎不起作用(不使用早期绑定)。