首页 > 解决方案 > Excel中条件格式的VBA访问代码

问题描述

我有一个将表格导出到 Excel 的数据库,并且我需要 Z 列中的单元格格式是基于 Y 列中的值的货币或百分比。我知道我可以在 Excel 中使用条件格式执行此操作,但我很难过如何在 Access 中执行此操作。

我试过这个

Sub GetExcel_INV_Hist(File_Path_Name)

Dim MyXL As Object

Set MyXL = CreateObject("Excel.Application")
    MyXL.Workbooks.Open (File_Path_Name)

    MyXL.Visible = True

' IHFormat Macro

MyXL.Application.Columns("Z:AC").Select
MyXL.Application.Selection.NumberFormat = "$#,##0.00_);[Red]($#,##0.00)"

MyXL.Application.Range("Z:Z").Select
MyXL.Application.Selection.NumberFormat = "0.00%"
MyXL.Application.Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
    "=$Y3 = ""GM"""
MyXL.Application.Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
MyXL.Application.ExecuteExcel4Macro "File_Path_Name!(2,1,""0.00%"")"
MyXL.Application.Selection.FormatConditions(1).StopIfTrue = False
MyXL.Application.Selection.Copy
MyXL.Application.Range("Z4").Select
MyXL.Application.Range(Selection, Selection.End(xlDown)).Select
MyXL.Application.Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False

首先将 Z 的格式更改为货币,然后我选择第一个单元格 Z3,检查是否 Y3 = GM,如果是,则将格式更改为百分比。然后选择 Z 的其余部分并进行选择性粘贴/格式。它在 ExecuteExcel4Macro 行引发错误。我假设是因为条件格式没有在过程创建的工作簿上完成。

提前感谢您的帮助。

编辑:我在 excel 中记录了宏,所以有问题的行是作为 excel 宏的一部分创建的。我已经扩展了我的代码,这是错误:

错误片段

其余的格式工作完美。

再次感谢

标签: excelvbams-accessconditional-formatting

解决方案


我猜您在跟踪所选内容时遇到了麻烦,而且Access不知道xlExpression (2)xlPasteFormats (-4122)xlNone (-4142)是什么意思。您需要改用数字等价物。

我对这条线感到惊讶MyXL.Application.ExecuteExcel4Macro "File_Path_Name!(2,1,""0.00%"")",但这就是我在录制宏来做这件事时得到的。我仍然会扔掉那条线并使用它NumberFormat = "£#,##0.00"

试试这个代码:

Sub Test()

    GetExcel_INV_Hist "C:\Path_To_My_Workbook\Book1.xlsx"

End Sub

Public Sub GetExcel_INV_Hist(File_Path_Name As String)

    Dim MyXL As Object
    Dim MyWB As Object

    Set MyXL = CreateXL

    Set MyWB = MyXL.Workbooks.Open(File_Path_Name)

    With MyWB.worksheets("Sheet1")
        .Columns("AA:AC").NumberFormat = "$#,##0.00_);[Red]($#,##0.00)"
        .Columns("Z:Z").NumberFormat = "0.00%"

        With .Columns("Z:Z")
            .FormatConditions.Add Type:=2, Formula1:="=$Y1=""GM""" '2 = xlExpression
            .FormatConditions(.FormatConditions.Count).SetFirstPriority
            With .FormatConditions(1)
                .NumberFormat = "$#,##0.00"
            End With
        End With

    End With

End Sub

Public Function CreateXL(Optional bVisible As Boolean = True) As Object

    Dim oTmpXL As Object

    On Error Resume Next
    Set oTmpXL = GetObject(, "Excel.Application")

    If Err.Number <> 0 Then
        Err.Clear
        On Error GoTo ERROR_HANDLER
        Set oTmpXL = CreateObject("Excel.Application")
    End If

    oTmpXL.Visible = bVisible
    Set CreateXL = oTmpXL

    On Error GoTo 0
    Exit Function

ERROR_HANDLER:
        MsgBox "Error " & Err.Number & vbCr & _
            " (" & Err.Description & ") in procedure CreateXL."
End Function

推荐阅读