我使用以下代码将数据从一个工作表复制到另一个工作表,每次复制新数据时都会将其插入一个新行。我希望能够将公式插入到活动/当前行的单元格D和E中,并使用动态单元格引用。所以如果第5行是A5,如果是第6行则是A6,依此类推。
我尝试过使用ActiveCell.Formula和DestRow,但没有任何效果。
有人可以告诉我如何才能实现这一目标吗?提前致谢
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.DisplayAlerts = False
If Target.Column = Range("Z1").Column And Range("Z" & ActiveCell.Row).Value = "SUBMIT" Then
Dim ws1 As Worksheet, ws2 As Worksheet
Dim DestRow As Long
Set ws1 = Sheets("Home")
Set ws2 = Sheets("Statistics")
DestRow = ws2.Cells(Rows.Count, "A").End(xlUp).Row + 1
ws1.Range("B10").Copy
ws2.Range("A" & DestRow).PasteSpecial xlPasteValuesAndNumberFormats
ws1.Range("B15").Copy
ws2.Range("B" & DestRow).PasteSpecial xlPasteValuesAndNumberFormats
ws1.Range("B20").Copy
ws2.Range("C" & DestRow).PasteSpecial xlPasteValuesAndNumberFormats
ws2.Range("D" & DestRow).Formula = "=IF(ISTEXT(A5),IF(E5 <>""Yes"",CONCATENATE(""NS"")&RANDBETWEEN(0,9)&RANDBETWEEN(0,9)&RANDBETWEEN(0,9)&RANDBETWEEN(0,9)&RANDBETWEEN(0,9)&RANDBETWEEN(0,9),D5),"""")"
ws2.Range("E" & DestRow).Formula = "=IF(ISTEXT(A5),IF(ISTEXT(D5),""Yes"",""N/A""),"""")"
ws1.Range("Y7").Copy
ws2.Range("F" & DestRow).PasteSpecial xlPasteValuesAndNumberFormats
ws1.Range("H10").Copy
ws2.Range("H" & DestRow).PasteSpecial xlPasteValuesAndNumberFormats
End If
End Sub
答案 0 :(得分:0)
您需要在公式中加入DestRow
。即您定义公式的两行应更改为:
ws2.Range("D" & DestRow).Formula = "=IF(ISTEXT(A" & DestRow & "),IF(E" & DestRow & " <>""Yes"",CONCATENATE(""NS"")&RANDBETWEEN(0,9)&RANDBETWEEN(0,9)&RANDBETWEEN(0,9)&RANDBETWEEN(0,9)&RANDBETWEEN(0,9)&RANDBETWEEN(0,9),D" & DestRow & "),"""")"
ws2.Range("E" & DestRow).Formula = "=IF(ISTEXT(A" & DestRow & "),IF(ISTEXT(D" & DestRow & "),""Yes"",""N/A""),"""")"