答案 0 :(得分:0)
以下示例将最后编辑的条目从Data
表复制到Form
表。将以下代码放入VBA项目中的Data
工作表:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Static objTargetCells As Object
Dim objTargetCell As Range
Dim strHeader As Variant
Dim objTargetSheet As Worksheet
Dim x As Long
Set objTargetSheet = Sheets("Form")
If objTargetCells Is Nothing Then
Set objTargetCells = CreateObject("Scripting.Dictionary")
x = 1
Do
strHeader = Target.Worksheet.Cells(1, x).Value
Set objTargetCell = objTargetSheet.Cells.Find(strHeader, , xlValues, xlWhole, xlByRows, xlNext, True, , False)
Set objTargetCells(strHeader) = objTargetCell.Offset(0, 1)
x = x + 1
Loop While Cells(1, x).Value <> ""
End If
With Target.Worksheet
If .Cells(1, Target.Column).Value <> "" And Target.Row <> 1 Then
x = 1
For Each strHeader In objTargetCells
objTargetCells(strHeader).Value = .Cells(Target.Row, x).Value
x = x + 1
Next
objTargetSheet.Cells.EntireColumn.AutoFit
End If
End With
End Sub
这是Data
工作表看起来像:
Form
工作表:
代码在每个Data
工作表更改事件上运行。第一次在Data
工作表上创建表字段字典,并在Form
工作表上使用对相应目标单元格的引用填充它。这些单元格可以通过.Find
方法找到,但您可以手动使用硬编码范围。