简体   繁体   English

使用Excel VBA将公式插入单元格

[英]Insert formula into cells using excel vba

I'm trying to follow this example , but it's not working. 我正在尝试遵循此示例 ,但是它不起作用。 Does offset cause a problem? offset会引起问题吗?

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. 请记住, formula_parse是正确的字符串形式。
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: 并且由于您正在以R1C1表示法传递公式,因此请更改以下行:

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

to this: 对此:

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

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

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