简体   繁体   English

VBA代码中的Excel公式

[英]Excel formula in VBA code

So, in Sheet1 I have base of some names and it looks like this: 因此,在Sheet1中我有一些名称的基础,它看起来像这样:

在此输入图像描述

In Sheet2 I'm working with these names from Sheet1. 在Sheet2中,我正在使用Sheet1中的这些名称。 I'm doing that in a way that I'm entering Code value in column A and in column BI get the Name, in column CI get the Last Name. 我这样做的方式是我在A列中输入Code值,在BI列中获取Name,在CI列中获取Last Name。 That looks like this: 看起来像这样:

在此输入图像描述

I've done this with formulas, entering it in the formula bar. 我用公式完成了这个,在公式栏中输入它。 For column A(or Name) I've used this formula: =IFERROR(VLOOKUP(A2;Sheet1!A:C;2;FALSE);"") and for column B(or Last Name) I've used this one: =IFERROR(VLOOKUP(A2;Sheet1!A:C;3;FALSE);"") . 对于A列(或名称),我使用了这个公式: =IFERROR(VLOOKUP(A2;Sheet1!A:C;2;FALSE);"")和B列(或姓氏)我用过这个: =IFERROR(VLOOKUP(A2;Sheet1!A:C;3;FALSE);"") I've dragged these formulas to row 20 and it works great. 我把这些公式拖到第20行,效果很好。

Now, what I'd like to do is to put these formulas into Excel VBA code and them to work for noted range. 现在,我想要做的是将这些公式放入Excel VBA代码中,并将它们用于指定的范围。 I've just started to use VBA and I don't know how to do it in it, tried something but doesn't work, ..., I've done this so far. 我刚刚开始使用VBA,我不知道如何在其中进行,尝试了一些但不起作用,...,到目前为止我已经完成了这个。 I'm new to this Excel/Macro/VBA thing so any help would be appreciated. 我是这个Excel /宏/ VBA的新手,所以任何帮助将不胜感激。

The below code will work if you type in your Code values in sheet2 and highlight them, and run this macro: 如果您在sheet2键入Code值并突出显示它们,并运行此宏,则以下代码将起作用:

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

Edit: If you are wanting to update values as you type use (thank you @PeterAlbert for added optimisation!): 编辑:如果您想在键入时更新值(感谢@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 of RC: RC的爆发:

The FormulaR1C1 formula types are good to use when referencing a cell with respect to the current cell. 当引用相对于当前单元格的单元格时, FormulaR1C1公式类型很好用。 There a few rules to remember: 要记住一些规则:

  • The R stands for Row and C is for Column and the integer after it, if any, defines the row or column; R代表Row, C代表Column,后面的整数(如果有的话)定义行或列;
  • As a basis the RC formula references itself; 作为RC公式参考的基础;
  • Any number following the R or C wraped in [] is an offset to itself, eg if you are in cell A1 and use R[1]C[1] you would be referencing cell B2 ; []中包含的RC之后的任何数字都是自身的偏移量,例如,如果您在单元格A1并使用R[1]C[1]您将引用单元格B2 ;
  • Also any number following the R and C is an exact, eg if you reference R2C2 no matter the cell you are in would also point to B2 ; RC之后的任何数字都是精确的,例如,如果您引用R2C2无论您所在的单元格是否也指向B2 ; and

To complicate things if you were in cell C5 , eg using Range("C5").FormulaR1C1 = and coded the follwing: 如果您在单元格C5 Range("C5").FormulaR1C1 =事情复杂化,例如使用Range("C5").FormulaR1C1 =并编码以下内容:

  1. "=RC[-1]" references cell B5 "=RC[-1]"引用单元格B5
  2. "=RC1" references cell A5 , more rightly $A5 "=RC1"引用单元格A5 ,更正确的是$A5
  3. "=R[1]C[-2]" references cell A6 "=R[1]C[-2]"参考单元格A6
  4. "=Sum(C[-1]:C5)" is =Sum(B:E) , more rightly =Sum(B:$E) "=Sum(C[-1]:C5)" =Sum(B:E) ,更正确=Sum(B:$E)

If I understand your question and comments correctly, you want to ensure that columns B&C always show you the right values based on your formula, but also want to protect (and maybe even hide the formula) from the users. 如果我正确理解您的问题和评论,您希望确保B&C列始终根据您的公式显示正确的值,但也希望保护(甚至可能隐藏公式)用户。

I'd suggest you use sheet protection instead: all you need to do is to unlock the cells you want the users to edit, ie select column A and in the _ Format cells_ dialog uncheck "Locked" in the Protection tab. 我建议您使用表单保护:您需要做的就是解锁您希望用户编辑的单元格,即选择A列,然后在_ Format cells_对话框中取消选中Protection选项卡中的“Locked”。 Similarly for columns B&C, check "Hidden". 同样,对于列B和C,请选中“隐藏”。 Now right click the sheet name and select Protect Sheet . 现在右键单击工作表名称并选择“ 保护工作表” Once this is done, the user can edit column A - but will not see the formula in B&C and cannot edit those cells. 完成此操作后,用户可以编辑A列 - 但不会在B&C中看到公式,也无法编辑这些单元格。

If for some reasons you need to ensure this in VBA, use the following code: 如果由于某些原因需要在VBA中确保这一点,请使用以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False 'to prevent endless loop
    With Target.Offset(, 2 - Target.Column).Resize(, 2)
        .FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C3,COLUMN(RC),0),"""")"
        .Value = .Value
    End With
    Application.EnableEvents = True
End Sub

You need to place this in the module of the worksheet. 您需要将其放在工作表的模块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM