为什么我的长公式给我一个语法错误?与“,”有关

时间:2019-07-26 18:04:16

标签: excel vba

因此,此宏在C和D中插入2列。然后将该公式一直填充到C列。

Option Explicit

Sub Format_dates()

    Dim ws As worksheet
    Dim lst As Long
    Dim i As Long
    Dim r As Long

    Columns("C:D").Insert Shift:=xlToRight
    Range("C2").Value = "START DATE"
    Range("D2").Value = "END DATE"

    Range("A" & Cells.Rows.Count).End(xlUp).Offset(0, 3).Select

    With ActiveSheet ' ("MASTER Business Events Calendar")

        lst = ws.Cells(.Rows.Count, 2).End(xlUp).row

        For i = 3 To lst
            r = Cells.row
            ws.Cells(i, 3) = "=IF(ISNUMBER(B&r),B&r,DATEVALUE(TRIM(LEFT(B&r,FIND("-",SUBSTITUTE(B&r,CHAR(150),"-")&"-")-1))&", "&RIGHT(B&r,4)))"
        Next i
    End With

End Sub

我不能像在使用python一样替换公式中的变量吗?

1 个答案:

答案 0 :(得分:1)

您需要将变量与字符串分开:

  

B&r

应该是

B" & r & "

所有"应该是""

ws.Cells(i, 3).Formula = "=IF(ISNUMBER(B" & r & "),B" & r & ",DATEVALUE(TRIM(LEFT(B" & r & ",FIND(""-"",SUBSTITUTE(B" & r & ",CHAR(150),""-"")&""-"")-1))&"", ""&RIGHT(B" & r & ",4)))"

另一个说明,您引用了ws,但从未设置。应该设置为

Set ws = ActiveSheet

然后删除With块。


也就是说,不需要循环。

ws.Range(ws.Cells(3, 3),ws.Cells(lst,3)).Formula = "=IF(ISNUMBER(B3),B3,DATEVALUE(TRIM(LEFT(B3,FIND(""-"",SUBSTITUTE(B3,CHAR(150),""-"")&""-"")-1))&"", ""&RIGHT(B3,4)))"

由于该行是相对的,因此将正确地进行迭代

Option Explicit

Sub Format_dates()

    Dim ws As worksheet
    Set ws = ActiveSheet


    ws.Columns("C:D").Insert Shift:=xlToRight
    ws.Range("C2").Value = "START DATE"
    ws.Range("D2").Value = "END DATE"

    Dim lst As Long
    lst = ws.Cells(ws.Rows.Count, 2).End(xlUp).row

    ws.Range(ws.Cells(3, 3),ws.Cells(lst,3)).Formula = "=IF(ISNUMBER(B3),B3,DATEVALUE(TRIM(LEFT(B3,FIND(""-"",SUBSTITUTE(B3,CHAR(150),""-"")&""-"")-1))&"", ""&RIGHT(B3,4)))"


End Sub