使用excel vba将公式插入单元格

时间:2015-03-17 02:00:10

标签: excel vba excel-vba

我正在尝试关注this example,但它无效。 offset会导致问题吗?

这就是我所拥有的:

Sub parse_dates_flurry()

    Dim col_diff As Integer '  how many columns away the unparsed date
    col_diff = -20

    Dim num_of_char As Integer
    num_of_char = 10

    Dim sheet_name_flurry As String
    sheet_name_flurry = "flurry_an_output.csv"

' get rows used in sheet
    Dim rows1 As Long
    rows1 = Get_Rows_Generic(sheet_name_flurry, 1)

'   find last column and fill with formula
    Dim formula_parse As String
    formula_parse = "=LEFT(RC[col_dif],num_of_char)"  ' 

    Dim starting_cell_range As Range
    Dim n As Long
    With Worksheets(sheet_name_flurry)
        Set starting_cell_range = .Range(find_last_column(sheet_name_flurry))
        starting_cell_range.Offset(0, 1) = "Parsed date" 

        For n = 1 To (rows1 - 1)
        '   getting error here:
            starting_cell_range.Offset(n, 1).Formula = formula_parse
        Next n   
    End With
End Sub

1 个答案:

答案 0 :(得分:2)

formula_parse = "=LEFT(RC[col_dif],num_of_char)"

应该是这样的:

formula_parse = "=LEFT(RC[" & col_dif & "]," & num_of_char & ")"

请记住,formula_parse是一种正确的字符串形式 但要将变量的值连接到它,你需要像上面那样进行 由于您要以R1C1表示法传递公式,请更改此行:

starting_cell_range.Offset(n, 1).Formula = formula_parse

到此:

starting_cell_range.Offset(n, 1).FormulaR1C1 = formula_parse