如果您在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
Explinatioin RC的:
FormulaR1C1
公式类型在引用与当前单元格相关的单元格时很适用。有一些规则要记住:
- 的
R
代表行和C
是柱和它,如果有的话,定义了行或列后的整数;
- 作为
RC
公式引用的基础;
- 中包含的
R
或C
之后的任何数字都是自身的偏移量,例如,如果您位于单元格A1
中并使用R[1]C[1]
,那么您将引用单元格B2
;
- 此外,
R
和C
之后的任何数字都是确切的,例如,如果您参考R2C2
,则无论您所在的单元格是否也指向B2
;和
如果您在单元格C5
(例如,使用Range("C5").FormulaR1C1 =
和编码的follwing:
"=RC[-1]"
引用细胞B5
"=RC1"
引用细胞A5
,更正确地$A5
"=R[1]C[-2]"
引用细胞A6
"=Sum(C[-1]:C5)"
是=Sum(B:E)
,更正确地=Sum(B:$E)
来源
2013-02-17 05:27:16
glh
你究竟想要宏做什么?如果你只想在一个范围内放置一个公式,你可以尝试类似'Range(“B2:B20”)。Formula =“= IFERROR(VLOOKUP(A2,Sheet1!A:C,2,FALSE);” “”)“' – 2013-02-16 22:57:28
显示”Excel VBA“代码(给出上下文)并解释*如何*它不起作用。 – 2013-02-16 23:05:07
好吧,首先你可以很容易地从单元格中删除公式,而不是你想要的。与宏,我认为这是另一回事。 – Sylca 2013-02-16 23:05:53