这个有点复杂,但我觉得可能有一个简单的方法。
如果列中的单元格发生更改,我希望找到包含该修改过的单元格的行,并将单元格从另一个工作表复制到该行中的其他列。
目前,我的代码将从列中的更改中复制另一个工作表中的单元格,但在单击鼠标时将其粘贴到单元格中。我正在寻找它自动粘贴到命名列(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
答案 0 :(得分: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中的单元格拖动到多个行,这段代码将不适用于所有受影响的行。您可能期望的任何其他行为吗?
答案 1 :(得分:0)
您需要的是target.Row
此外,由于您使用的是Worksheet_Change
,我建议您查看THIS链接。
已经过测试
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