简体   繁体   中英

Insert formula into cells using excel vba

I'm trying to follow this example , but it's not working. Does offset cause a problem?

Here's what I have:

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
formula_parse = "=LEFT(RC[col_dif],num_of_char)"

Should be like this:

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

Remember that formula_parse is in a form of string which is correct.
But to concatenate the value of a variable to it, you'll need to do it like above.
And since you are passing a formula in R1C1 notation, change this line:

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

to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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