VBA中可能出现的单元引用错误[R1C1样式]

时间:2014-09-15 12:21:13

标签: excel vba excel-vba

我在运行这个宏时遇到了问题 - 它之前有效,但现在第6行在新计算机上给出了一个错误(也是新版本的Excel)。这里有明显的问题吗?

Sub CalculateDifferences()

Dim Col As Long

Col = Worksheets("AgedDebtors").Range("Z2").End(xlToLeft).Column

Worksheets("AgedDebtors").Range("Z2").End(xlToLeft).Value = "Difference"
Worksheets("AgedDebtors").Range("H1").Value = Worksheets("PivotTable").Range("Z2").End(xlToLeft).Column - 2
Worksheets("AgedDebtors").Range(Cells(3, Col), Cells(Range("A65535").End(xlUp).Row, Col)).Formula = "=$G3 - VLOOKUP($F3,PivotTable!$A$2:$J$3500, $H$1, FALSE)"
End Sub

1 个答案:

答案 0 :(得分:2)

您没有使用工作表限定两个Cell(和一个额外的Range)调用:

Worksheets("AgedDebtors").Range(Worksheets("AgedDebtors").Cells(3, Col), Worksheets("AgedDebtors").Cells(Worksheets("AgedDebtors").Range("A65535").End(xlUp).Row, Col)).Formula = "=$G3 - VLOOKUP($F3,PivotTable!$A$2:$J$3500, $H$1, FALSE)"

但你可以用With...End With块来整理它:

Sub CalculateDifferences()

Dim Col As Long
with Worksheets("AgedDebtors")
Col = .Range("Z2").End(xlToLeft).Column

.Range("Z2").End(xlToLeft).Value = "Difference"
.Range("H1").Value = Worksheets("PivotTable").Range("Z2").End(xlToLeft).Column - 2
.Range(.Cells(3, Col), .Cells(.Range("A65535").End(xlUp).Row, Col)).Formula = "=$G3 - VLOOKUP($F3,PivotTable!$A$2:$J$3500, $H$1, FALSE)"
end with
End Sub