如果您输入Code
值sheet2
并突出显示它们,然后运行此宏,则以下代码将起作用:
Selection.Offset(0, 1).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],Sheet1!C[-1]:C,2,FALSE),"""")"
Selection.Offset(0, 2).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-2],Sheet1!C[-2]:C,3,FALSE),"""")"
Selection.Offset(0, 1).Value = Selection.Offset(0, 1).Value
Selection.Offset(0, 2).Value = Selection.Offset(0, 2).Value
编辑:如果您想在键入时更新值,请使用(感谢@PeterAlbert 增加优化!):
Private Sub Worksheet_Change(ByVal Target As Range)
'end if the user made a change to more than one cell at once?
If Target.Count > 1 Then End
'stop system activating worksheet_change event while changing the sheet
Application.EnableEvents = False
'continue if column 1(A) was updated
'and
'dont continue if header or row 1 was changed
If Target.Column = 1 And Target.Row <> 1 Then
With Target.Offset(0, 1) 'alter the next cell, current column +1 (column B)
'RC1 = current row and column 1(A) e.g. if A2 was edited, RC1 = $B2
'C1:C2 = $A:$B
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C2,2,FALSE),"""")"
.Value = .Value 'store value
End With
With Target.Offset(0, 2) 'alter the next cell, current column +2 (column C)
'C1:C3 = $A:$C
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C3,3,FALSE),"""")"
.Value = .Value 'store value
End With
End If
Application.EnableEvents = True 'reset system events
End Sub
RC的解释:
当FormulaR1C1
引用一个相对于当前单元格的单元格时,公式类型非常适合使用。有几条规则要记住:
- The
R
代表 Row 并且C
是 Column 和它后面的整数,如果有的话,定义行或列;
- 作为基础,
RC
公式引用自身;
R
或C
包裹在后面的任何数字[]
都是对自身的偏移,例如,如果您在单元格中A1
并使用R[1]C[1]
,您将引用单元格B2
;
- 此外,
R
and之后的任何数字C
都是精确的,例如,如果您引用R2C2
无论您在哪个单元格中,都将指向B2
; 和
如果您在 cell 中,会使事情复杂化C5
,例如使用Range("C5").FormulaR1C1 =
和编码以下内容:
"=RC[-1]"
参考单元格B5
"=RC1"
引用单元格A5
,更正确$A5
"=R[1]C[-2]"
参考单元格A6
"=Sum(C[-1]:C5)"
更=Sum(B:E)
正确的是=Sum(B:$E)