excel IfAnd宏,但仅用于第一行,需要为所有行添加一个循环

iqjalb3h  于 2023-10-22  发布在  其他
关注(0)|答案(3)|浏览(78)

我创建了一个if和,但需要添加一个循环。无法使循环工作。

Sub IfAnd()

If Range("j2") = "9-99-9998" And Range("f2") <> 2 Then
Range("k2").Value = "Indirect"
Else
If Range("j2") = "9-99-9998" And Range("F2") = 2 Then
Range("k2").Value = "IndirectOT"
Else
If Range("j2") <> "9-99-9998" And Range("F2") <> 2 Then
Range("k2").Value = "Direct"
Else
If Range("j2") <> "9-99-9998" And Range("F2") = 2 Then
Range("k2").Value = "DirectOT"
End If
End If
End If
End If

End Sub

创建了一个数组,但没有工作

q1qsirdb

q1qsirdb1#

Option Explicit

Sub IfAnd()
    Dim r As Long, s As String
    For r = 2 To 3
        If Cells(r, "J") = "9-99-9998" Then
            s = "Indirect"
        Else
            s = "Direct"
        End If
        
        If Cells(r, "F") = 2 Then
            s = s & "OT"
        End If
        Cells(r, "K") = s
   Next
End Sub
3df52oht

3df52oht2#

下面是另一种使用Loops的方法。

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Set ws = Sheet1 '<~~ Change this to the relevant sheet
    
    Dim LastRow As Long
    LastRow = ws.Range("F" & ws.Rows.Count).End(xlUp).Row
    
    Dim rng As Range
    Set rng = ws.Range("K2:K" & LastRow)
    
    With rng
        .Formula = "=IF(J2=""9-99-9998"",IF(F2=2,""IndirectOT"",""Indirect""),IF(F2=2,""DirectOT"", ""Direct""))"
        .Value = .Value
    End With
End Sub
wh6knrhe

wh6knrhe3#

您可以将If-And检查与实际循环隔离开来,这样从长远来看可以更容易地进行修改。

Option Explicit

Sub test()
    Dim serialNumbers As Range
    Set serialNumbers = Sheet1.Range("J2:J100")

    Dim categories As Range
    Set categories = Sheet1.Range("F2:F100")
    
    Dim laborTypes As Range
    Set laborTypes = Sheet1.Range("K2:K100")
    
    Dim serialNumber As Variant
    For Each serialNumber In serialNumbers
        Dim category As Variant
        For Each category In categories
            Dim laborType As Variant
            For Each laborType In laborTypes
                IfAnd serialNumber, category, laborType
            Next laborType
        Next category
    Next serialNumber
End Sub

Sub IfAnd(serialNumber As Range, category As Range, laborType As Range)
    If (serialNumber = "9-99-9998") And (category <> 2) Then
        laborType = "Indirect"
    ElseIf (serialNumber = "9-99-9998") And (category = 2) Then
        laborType = "IndirectOT"
    ElseIf (serialNumber <> "9-99-9998") And (category <> 2) Then
        laborType = "Direct"
    ElseIf (serialNumber <> "9-99-9998") And (category = 2) Then
        laborType = "DirectOT"
    End If
End Sub

相关问题