1

我对 vba 编码很陌生。在工作表中,我试图通过检查同时列 J、K、O 中的条件来使用宏列(Q)添加一个附加列。因此,如果某些条件在每一列中传递,我希望在 Q 中输入一个值列对应的行。这是我放在一起的一段代码。

Option Explicit

Sub Button2_Click()

Sheet1.Activate

Dim i As Long
    
    For i = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
    'Check so that we only process non-empty cells
    '(just in case there is an empty cell part-way through the data)
        If Cells(i, 10).Value = "No" And Cells(i, 15) <= 0 Then
        Cells(i, 17) = "Pending with employee"
        Else
        If Cells(i, 10).Value = "No" And Cells(i, 15) >= 0 And Cells(i, 11) = "No Action Pending" Then
        Cells(i, 17) = "Pending with employee"
        Else
        If Cells(i, 10).Value = "No" And Cells(i, 15) >= 0 And Cells(i, 11) = "Pending With Manager" Then
        Cells(i, 17) = "Pending with Manager"
        Else
        If Cells(i, 10).Value = "Yes" And Cells(i, 15) >= 0 And Cells(i, 11) = "No Action Pending" Then
        Cells(i, 17) = "All Done"
        
        'If Not IsEmpty(.Cells(i, "B").Value) Then
         ' If .Cells(i, "E").Value = "NA" Then'
         'ThisWorkbook.Worksheets("CTCto TCC Conversion").Cells(i, "F").Value = "NA" '
         
                End If
         
         End If
         End If
          End If
          
        Next i
        
    End With
        MsgBox "Column Created"
 End Sub

它给我一个错误无效或不合格的参考。如果有任何错误需要纠正才能运行代码,请帮助我。

谢谢

4

1 回答 1

1

使用With语句

  • BigBen 已经回答了你的问题。这是一个额外的例子。
  • 检查包含.Cells(i, 15).Value. 其中一个可能应该删除等号。
  • 如果您在一行代码中编写多个条件,即使第一个条件已经True(或False),它们都将被评估,这使得它比在新行中编写每个条件效率低。在实践中,您通常不会感到有什么不同。不过,我无法决定哪一个对您来说更具可读性或可维护性。
Option Explicit

Sub Button2_Click()

    With Sheet1
        Dim i As Long
        For i = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
            If .Cells(i, 10).Value = "No" Then
                If .Cells(i, 15).Value <= 0 Then
                    .Cells(i, 17).Value = "Pending with employee"
                Else
                    If .Cells(i, 11).Value = "No Action Pending" Then
                        .Cells(i, 17).Value = "Pending with employee"
                    ElseIf .Cells(i, 11).Value = "Pending With Manager" Then
                        .Cells(i, 17).Value = "Pending with Manager"
                    End If
                End If
            ElseIf .Cells(i, 10).Value = "Yes" Then
                If .Cells(i, 15).Value >= 0 Then
                    If .Cells(i, 11).Value = "No Action Pending" Then
                        .Cells(i, 17).Value = "All Done"
                    End If
                End If
            End If
        Next i
    End With
    
    MsgBox "Column Created"

End Sub
于 2021-08-28T03:27:45.867 回答