0

这个有点复杂,但我觉得可能有一个简单的方法来做到这一点。

如果更改了列中的单元格,我希望找到包含该修改单元格的行并将单元格从另一张表复制到该行中的不同列。

目前,我的代码将在列中更改时从另一张表中复制单元格,但在单击鼠标时将其粘贴到单元格中。我正在寻找它自动粘贴到命名列(H)中。

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 6 And (Target.Row >= 1 And Target.Row <= 10000) Then

Sheets("Sheet2").Range("B2:B2").Copy

End If

Dim lastRow As Long
With ActiveSheet
Sheets("Sheet1").Activate
lastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
Selection.PasteSpecial xlPasteValues

End With  

End Sub
4

2 回答 2

0

你想做这样的事情吗?

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim val As String
    val = Sheets("Sheet2").Range("B2").Value
    If Target.Column = 6 And (Target.Row >= 1 And Target.Row <= 10000) Then
        'Whatever column
        Sheets("Sheet1").Range("H" & Target.Row).Value = val
    End If
End Sub

如果发生这种情况,您尝试将 F 列中的单元格拖动到多行,这段代码将不适用于所有受影响的行。也许还有其他你可能期待的行为?

于 2013-10-03T08:11:36.847 回答
0

你需要的是target.Row

另外,由于您使用的是Worksheet_Change,我建议您查看链接。

久经考验

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

    '~~> If there was a multiple change then exit sub
    If Target.Cells.CountLarge > 1 Then Exit Sub

    Application.EnableEvents = False

    '~~> This is the sheet from where the data needs to be copied
    Dim sourceWs As Worksheet
    Set sourceWs = ThisWorkbook.Sheets("Sheet2")

    '~~> Check if the change happened in Col 6
    If Not Intersect(Target, Columns(6)) Is Nothing Then
        '~~> Get the value in Col H
        Range("H" & Target.Row).Value = sourceWs.Range("B2").Value
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub
于 2013-10-03T08:12:26.857 回答