Excel VBA:用if条件连接公式

Excel VBA: concatenate formula with if condition

我正在尝试使用以下编码根据条件连接单元格。它抛出语法错误。你能帮我更正这段代码吗,还是我需要使用其他方法。

要求:

代码:

Sub Conc()
Dim lastrow As Range
Dim str As String


With Worksheets("sheet1")
lastrow = .Cells(Rows.Count, "A").End(xlUp).Row
Range("F2").Select

Range("F2:F" & LastRow).Formula = "=IF(B2="aaa@to.com",CONCATENATE(E2," -",MID(A2,FIND("SECN",A2),14)),IF(B2<>"aaa@to.com",CONCATENATE(MID(A2,FIND("SECN",A2),14)," - ",C2)))"
End With

结束子

首先,您需要在公式字符串中加倍 "

其次,您需要完全限定嵌套在 With Worksheets("sheet1") 语句中的所有 CellsRows.CountRange 对象。

第三,在设置 Formula 之前不需要 Select Range

With Worksheets("sheet1")
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    .Range("F2:F" & LastRow).Formula = "=IF(B2=""aaa@to.com"",CONCATENATE(E2,"" - "",MID(A2,FIND("" SECN"",A2),14)),IF(B2<>""aaa@to.com"",CONCATENATE(MID(A2,FIND(""SECN"",A2),14),"" - "",C2)))"
End With

这是更新后的代码...问题出在 lastrow 定义上,感谢@Gary 的学生和@Shai Rado 对公式的宝贵建议..

Sub Conc()

    Dim lastRow As Long

    With Worksheets("sheet1")
         lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
        .Range("F2:F" & lastRow).Formula = "=IF(B2=""aaa@to.com"",CONCATENATE(E2,"" - "",MID(A2,FIND(""SECN"",A2),14)),IF(B2<>""aaa@to.com"",CONCATENATE(MID(A2,FIND(""SECN"",A2),14),"" - "",C2)))"
    End With
End Sub