簡體   English   中英

如果兩個單元格連續匹配,則需要在excel vba中給一個名稱命名,而下一行匹配則需要動態給另一個名稱命名

[英]If two cells match’s in a row then need to give one name and next row match’s need to give another name dynamically in excel vba

我有點困惑編寫excel vba代碼。 請幫幫我。 這是我的要求

如果兩個單元格連續匹配,則需要給出一個名稱,而下一行匹配則需要通過excel vba中的循環動態地給另一個名稱

如果cell-A = 1且cell-B = 2,則再次命名第一名,如果macthes下一行是第二名

在此處輸入圖片說明

我的代碼是

Sub fill_name()
    Dim i As Integer
    Dim nm As String
    Dim j As Integer
    Dim f_name() As String

    For i = 1 To 4

        ReDim f_name(2)
        For j = 1 To 2
            f_name(j) = Cells(j, 12).Value

            If Cells(i, 1).Value = "1" And Cells(i, 3).Value = "2" Then
                Cells(i, 2).Value = f_name(j)
            End If

        Next j
    Next i

End Sub

您不需要VBA。 您可以通過公式來實現

將此公式放在B2並將其下拉

=IF(AND(A2=1,C2=2),IF(COUNTIF($B$1:$B1,"Hi")=COUNTIF($B$1:$B1,"Hello"),"Hi","Hello"),"")

在此處輸入圖片說明

如果您仍想使用VBA,請使用上述公式,例如

Sub fill_name()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim sFormula As String

    sFormula = "=IF(AND(A2=1,C2=2),IF(COUNTIF(" & _
               "$B$1:$B1,""Hi"")=COUNTIF($B$1:$B1,""Hello"")" & _
               ",""Hi"",""Hello""),"""")"

    '~~> Change this as per your requirement
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        With .Range("B2:B" & lRow)
            .Formula = sFormula
            .Value = .Value
        End With
    End With
End Sub

如果您不想使用公式而是想要循環,請像這樣使用它

Sub fill_name()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim i As Long, j As Long
    Dim MyAr(1 To 2) As String

    MyAr(1) = "Hi"
    MyAr(2) = "Hello"
    j = 1

    '~~> Change this as per your requirement
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lRow
            If .Range("A" & i).Value = 1 And .Range("C" & i).Value = 2 Then
                .Range("B" & i).Value = MyAr(j)
                If j = 1 Then j = 2 Else j = 1
            End If
        Next i
    End With
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM