VBA,如果范围内的活动单元格不等于String调用宏

时间:2017-04-20 11:28:13

标签: excel excel-vba vba

我对VBA世界很陌生。我正在尝试添加到现有的私有子(更改)。当范围内的活动单元格(“K2:K700”)不等于单词“向下”时,我试图“触发”宏“DelRCE”。

以下代码无效:

Dim txt As String
Dim rng As Range
Dim vec As String

txt = ActiveCell.Value
rng = ("K2:K700")
vec = "Down"

If r_ng.txt <> vec Then
    Call Macro
End If

3 个答案:

答案 0 :(得分:0)

我认为你正在寻找这样的东西:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim ws As Worksheet
    Dim key As String
    Dim rng As Range

    'Set the word you want to search for. Take capital letters into account
    key = "down"

    'Set worksheet to the first sheet in your workbook
    Set ws = ThisWorkbook.Sheets(1)

    'Change this to the range you want to search
    Set rng = ws.Range("A1:A100")

    'Check if the target is in the range
    If Not Intersect(Target, rng) Is Nothing Then
        If Target.Value <> key Then
        'Change this to you function call
            MsgBox "The target is inside the range and the value is different from '" & key & "'"
        End If
    End If

End Sub

答案 1 :(得分:0)

将光标置于test_Change子区域内并点击PF5以运行它。

private Sub Change()
Dim txt As String
Dim rng As Range
Dim vec As String
    txt = ActiveCell.Value
    rng = ("K2:K700")
    vec = "Down"

   If r_ng.txt <> vec Then
    Call DelRCE ' or "Run DelRCE" if it is a function
   End If
End Sub

Private Sub test_Change()
    call Change
End Sub

答案 2 :(得分:0)

将以下代码添加到Worksheet_Change事件:

下的相关工作表模块中
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

Dim vec As String
vec = "Down"

If Not Intersect(Target, Range("K2:K700")) Is Nothing Then ' check that modifed cell is inside the Range("K2:K700")
    If Target.Count > 1 Then Exit Sub ' Optional :  if more than 1 cell selected exut the sub

    If Not Target.Value Like vec Then ' Also possible to use: If Target.Value <> vec
        Call Macro
    End If
End If

End Sub