我正在从互联网上学习在 VBA 中创建公式,我在 excel 校园里看到了 Jon 的这篇文章,他在那里教他为百分比变化创建公式。
但是,我无法理解代码的一部分,他在创建公式时使用了双引号和 & 符号。
sFormula = "=IFERROR((" & sNew & " - " & sOld & ")/" & sOld & ",0)"
有人可以告诉我为什么在 sNew 和 sOld 之间使用 & 符号,以及为什么不使用引号和 & 符号会导致代码失败?
完整编码如下——
Sub Percent_Change_Formula()
'Description: Creates a percentage change formula
'Source: https://www.excelcampus.com/vba/percentage-change-formulas-macro/
Dim rOld As Range
Dim rNew As Range
Dim sOld As String
Dim sNew As String
Dim sFormula As String
'End the macro on any input errors
'or if the user hits Cancel in the InputBox
On Error GoTo ErrExit
'Prompt the user to select the cells
Set rNew = Application.InputBox( _
"Select the cell that contains the NEW number", _
"Select New Cell", Type:=8)
Set rOld = Application.InputBox( _
"Select the cell that contains the OLD number", _
"Select Old Cell", Type:=8)
'Get the cell addresses for the formula - relative references
sNew = rNew.Address(False, False)
sOld = rOld.Address(False, False)
'Create the formula
sFormula = "=IFERROR((" & sNew & " - " & sOld & ")/" & sOld & ",0)"
'Create the formula in the activecell
ActiveCell.Formula = sFormula
ErrExit:
End Sub