简体   繁体   English

VBA:如何用IF条件填充一列

[英]VBA: How to populate one column with IF condition

So here's my problem. 所以这是我的问题。 I've 3 columns with headers. 我有3列带有标题。 And for this example let's say the first column is a normal text string. 对于本示例,假设第一列是普通文本字符串。 The second one is an optional field, which is either empty or filled. 第二个是可选字段,可以为空或填充。 The third column is the one to be populated with the following rule: If the 2nd column is not empty, then the first 2 letters of the 1st column should be auto populated to 3rd column. 第三列是使用以下规则填充的列:如果第二列不为空,则第一列的前2个字母应自动填充到第三列。 See the picture below. 参见下图。

Example table 示例表

With functions all I'd have to do is to put =IF(B2 <> ""; LEFT(A2;2); "") -formula to all cells in 3rd column. 对于函数,我要做的就是将= IF(B2 <>“”; LEFT(A2; 2);“”)-公式放到第三列的所有单元格中。 But could someone tell me how would I do the same in VBA? 但是有人可以告诉我如何在VBA中做同样的事情吗? (I have no choice to use the function in this case). (在这种情况下,我别无选择地使用该功能)。

Edit: Thank you for all the answers :) 编辑:谢谢你所有的答案:)

Sub Macro1()
    ActiveCell.FormulaR1C1 = "=IF(R[5]C[11]<>"""",LEFT(R[5]C,2),"""")"

    'CHANGE C1:C38 TO THE RANGE OF YOUR THIRD COLUMN
    Selection.AutoFill Destination:=Range("C1:C38"), Type:=xlFillDefault

End Sub

Just adjust C1:C38 to suit your third column range 只需调整C1:C38以适合您的第三列范围

This should do it, 应该这样做

Sub test()
  Sheets("Sheet1").Range("C1:C10").Formula = "=IF(C1 <> """", LEFT(C1,2), """")"
End Sub

Considering the data you showed, give this a try... 考虑到您显示的数据,请尝试一下...

Sub InsertFormula()
Dim lr As Long
lr = Cells(Rows.Count, 1).End(xlUp).Row
Range("C2:C" & lr).Formula = "=IF(N2 <> """", LEFT(A2,2), """")"
End Sub

The above code assumes that the data lies in column A and B and you need to place the formula in column C starting from Row2 based on the column N. 上面的代码假定数据位于A列和B列中,并且您需要将公式从C列的C列开始,该列基于N列从Row2开始。

Public Function myThirdColumn(myFirstColumn, mySecondColumn)
    If mySecondColumn <> "" Then
        myThirdColumn = Left(myFirstColumn, 2)
    Else
        myThirdColumn = ""
    End If
End Function

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

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