0

主要工作表:

学生 | 等级 | 目标代码 | 目标文本

吉姆 | 一个 | 代码1 | 这是与 Code1 对应的文本

查找表,在名为“目标”的工作表中定义为“名称”“目标代码”:

代码1 | 这是与 Code1 对应的文本

代码2 | 这是与 Code2 对应的文本

我需要一些 VBA,以便在更改任何记录的 TargetCode 字段时,将相应的文本以文本形式放置到 Target Text 列中。我不能在 Target Text 列中使用 LOOKUP,因为文本需要是可编辑的,如果你尝试编辑它,你只是在编辑 LOOKUP 公式。任何形式的帮助将不胜感激。

我已经从 StackExchange 的其他部分中挑选了一些代码:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell_to_test As Range, cells_changed As Range
Dim result As String
Dim sheet As Worksheet

    Set cells_changed = Target(1, 1)
    Set cell_to_test = Range("D2")

    If Not Intersect(cells_changed, cell_to_test) Is Nothing Then 

        Set sheet = ActiveWorkbook.Sheets("Persuasive Speaking")
        Set TargetSheet = ActiveWorkbook.Sheets("Targets")
        result = Application.WorksheetFunction.Lookup(sheet.Range("D2"),     sheet.Range("WritingTargets"))
        MsgBox ("Test")
    End If
End Sub-

但我收到错误“对象'_Worksheet'的方法'范围'失败......

非常感谢任何帮助。

4

1 回答 1

1
Private Sub Worksheet_Change(ByVal Target As Range)

Const COL_IDS As Long = 3
Const COL_TARG_TEXT As Long = 4

Dim rngIds As Range, c As Range, val
Dim rngTable As Range, tmp, result

    On Error GoTo haveError

    Set rngIds = Application.Intersect(Target, Target.Parent.Columns(COL_IDS))

    If Not rngIds Is Nothing Then
        Set rngTable = ThisWorkbook.Sheets("Targets").Range("TargetCodes")
        For Each c In rngIds.Cells
            tmp = Trim(c.Value)
            If Len(tmp) > 0 Then
                val = Application.VLookup(tmp, rngTable, 2, False)
                'disable events to avoid re-triggering this sub                 
                Application.EnableEvents = False
                c.EntireRow.Cells(COL_TARG_TEXT).Value = _
                                    IIf(IsError(val), "Not found!", val)
                Application.EnableEvents = True
            End If
        Next c
    End If

    Exit Sub

haveError:
    'MsgBox Err.Description
    Application.EnableEvents = True

End Sub
于 2013-01-10T18:58:42.060 回答