【问题标题】: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 中动态给出另一个名称
【发布时间】:2016-08-04 16:06:33
【问题描述】:

我对编写 excel vba 代码有点困惑。请帮帮我。 这是我的要求

如果两个单元格连续匹配,则需要给出一个名称,下一行匹配需要通过excel vba中的循环动态地给出另一个名称

如果单元格-A = 1 和单元格-B = 2 则再次输入第一个名称,如果下一行是第二个名称

我的代码是

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 而不是公式?

标签: excel vba


【解决方案1】:

您不需要 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

【讨论】:

  • 抱歉回复晚了,感谢您的解决方案 Siddharth Rout
猜你喜欢
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多