“需要对象”带有 For 循环的 vba 的对象或范围引用

问题描述 投票:0回答:1

我使用 vba 来评估 2 列,并填充文本或根据 2 个日期之间的比较来更改颜色。看来这应该很容易。

我对VBA不是很精通,所以我很难知道何时使用(范围参考).Value。

我收到错误 424 需要对象。突出显示

Set = Actual
部分代码。

如果有经验丰富的编码员提供任何帮助,我们将不胜感激!

Sub ColorTATCol()

Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Plate Analysis")

 With ws

 Dim LR As Long
 LR = Sheet1.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

  Dim i As Long
  Dim Actual As Date
  Dim Projected As Date

    For i = 3 To LR

     Set Actual = Cells(i, "P").Value
     Set Projected = Cells(i, "O").Value
     
     'If ActualTAT row is empty, ActualTAT = "not complete"
     'If ProjectedTAT row is empty, ProjectedTAT = "no receipt date"
     If IsEmpty(Actual.Value) = True Then
     Actual.Value = "not complete"
     If IsEmpty(Projected.Value) = True Then
     Projected.Value = "no receipt date"
     End If
    End If
    'if ActualTAT is a Date And <= Projected TAT, interior color index = 8 (blue)
    If IsDate(Actual.Value) = True And Actual.Value <= Projected.Value Then
    Actual.Value.Interior.ColorIndex = 8
      'if ActualTAT > Projected TAT, interior color index = 4 (green)
      Else
      Actual.Value.Interior.ColorIndex = 4
      End If
    Next i
 End With
End Sub```
excel vba for-loop if-statement conditional-statements
1个回答
0
投票

也许更像这样:

Sub ColorTATCol()

    Dim ws As Worksheet
    Dim LR As Long, i As Long, ci As Long
    Dim Actual As Range, Projected As Range '## not as Date
    
    Set ws = ActiveWorkbook.Sheets("Plate Analysis")
    
    LR = ws.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    
    For i = 3 To LR
    
        Set Actual = ws.Cells(i, "P")
        Set Projected = ws.Cells(i, "O")
    
        'If ActualTAT row is empty, ActualTAT = "not complete"
        'If ProjectedTAT row is empty, ProjectedTAT = "no receipt date"
        If IsEmpty(Actual.Value) Then Actual.Value = "not complete"
        If IsEmpty(Projected.Value) Then Projected.Value = "no receipt date"
        
        'if ActualTAT is a Date And <= Projected TAT, interior color index = 8 (blue)
        If IsDate(Actual.Value) And Actual.Value <= Projected.Value Then
            Actual.Interior.ColorIndex = 8
        'if ActualTAT > Projected TAT, interior color index = 4 (green)
        Else
            Actual.Interior.ColorIndex = 4
        End If
    Next i
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.