在备用表中运行VBA代码触发错误的结果 – 尽pipe引用?

下面的代码试图从“input”表格中的一个单元格拉出数值,然后将其显示在“输出”表格中。 然后显示logging的最后一个值之间的差异,并以百分比表示该数字。

当我运行这个代码与输出表活动它的作品。 但是,当我从输出表运行它不。 而是在input工作表中显示我希望在列F中复制的值,并在输出工作表中的错误单元格中显示差异和百分比差异。

它看起来正确地引用了我,但它显然不是。 思考如何纠正?

我很欣赏代码可以更整洁 – 我对此很新。

Sub Button1_Click() Dim LastRow As Long Dim RecentRow As Long With Sheets("Output") LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row RecentRow = .Cells(.Rows.Count, "F").End(xlUp).Offset(1, 0).Row Range("F" & LastRow).Select ActiveCell.Offset(1, 0).Formula = "=Input!B4" ActiveCell.Offset(1, 0).Copy ActiveCell.Offset(1, 0).PasteSpecial (xlValues) End With ActiveCell.Offset(0, 1).Formula = "=(F" & RecentRow & "-F" & LastRow & ")" ActiveCell.Offset(0, 2).Formula = "=((F" & RecentRow & "/F" & LastRow & ")-1)" End Sub 

谢谢。

下面的代码应该解决你的问题 – 这是因为你的范围(“F”和LastRow).Select没有一个时间段之前的范围。

 Sub Button1_Click() Dim LastRow As Long Dim RecentRow As Long With Sheets("Output") LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row RecentRow = .Cells(.Rows.Count, "F").End(xlUp).Offset(1, 0).Row With .Range("F" & LastRow) .Offset(1, 0).Formula = "=Input!B4" .Offset(1, 0).Copy .Offset(1, 0).PasteSpecial (xlValues) .Offset(0, 1).Formula = "=(F" & RecentRow & "-F" & LastRow & ")" .Offset(0, 2).Formula = "=((F" & RecentRow & "/F" & LastRow & ")-1)" End With End With End Sub 

此外,您可以通过以下方式获得更高的代码效率:

 Sub Button1_Click() Dim LastRow As Long With ThisWorkbook.Sheets("Output") 'Allow for code to work even if in another workbook. LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row With .Range("F" & LastRow) .Offset(1, 0).Value2 = ThisWorkbook.Sheets("Input").Range("B4").Value2 .Offset(0, 1).Formula = "=(F" & LastRow + 1 & "-F" & LastRow & ")" .Offset(0, 2).Formula = "=((F" & LastRow + 1 & "/F" & LastRow & ")-1)" End With End With End Sub