用于查找特定文本的Excel VBA脚本

时间:2017-05-15 15:13:54

标签: excel vba if-statement

所以我添加了一张图片,以便您可以确切了解我需要做什么 - Excel sheet picture

所以我有这个脚本:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim A As Range, G, L, N As Range, Inte As Range, r As Range
    Set A = Range("F:F,K:K,M:M")
    Set Inte = Intersect(A, Target)
       If Inte Is Nothing Then Exit Sub
    Application.EnableEvents = False
        For Each r In Inte
             If r.Offset(0, 1).Value = "" Then
               r.Offset(0, 1).Value = Date
            End If
        Next r
    Application.EnableEvents = True

End Sub

我们只讨论我们在图片中看到的内容:所以现在当我在F列中写任何内容时,它会在G列中给出日期,我希望它只会在我提供日期时给出日期写" Ja" (德语是)或"是"

简单就是这样。我试图找到任何" if"命令,但我没有工作。 希望你能帮助我

谢谢! 丹尼尔

2 个答案:

答案 0 :(得分:0)

这是一个更好的实践,你需要将Application.EnableEvents设置为True,当你在下一次提出事件时存在方法时,也可以做一些“保持住” “如果出现问题,请使用错误捕获:

   Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo ende

    Application.EnableEvents = False


        Set A = Range("F:F,K:K,M:M")
        Set Inte = Intersect(A, Target)

        If Inte Is Nothing Then
        Application.EnableEvents = True
             Exit Sub
        End If

     For Each cel In Target

        r = cel.Row
        c = cel.Column

            If Trim(LCase(Cells(r, c))) = "yes" Or Trim(LCase(Cells(r, c))) = "ja" Then
                 Cells(r, c + 1) = Format(Date, "dd.MM.yyyy")
            Else
                  ' do something else
            End If
     Next

ende:
    Application.EnableEvents = True
    End Sub

答案 1 :(得分:0)

这个怎么样?

Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim rng As Range
Set rng = Range("F:F,K:K,M:M")
On Error GoTo SkipError
Application.EnableEvents = False
If Not Intersect(Target, rng) Is Nothing Then
    For Each cell In Target
        If LCase(VBA.Trim(cell.Value)) = "yes" Then
            cell.Offset(0, 1) = Date
        End If
    Next cell
End If
SkipError:
Application.EnableEvents = True
End Sub