简体   繁体   English

Excel VBA 将公式动态添加到最后一列的单元格

[英]Excel VBA Dynamically add formula to cell in last column

I'm new to VBA and am looking for a way to add a formula to the last column of my worksheet.我是 VBA 的新手,正在寻找一种将公式添加到工作表最后一列的方法。 The problem is that the number of columns before this column will change.问题是该列之前的列数会改变。 My code thus far is:到目前为止,我的代码是:

Dim LastColumn As Long
Dim LastRow As Long
Dim r, count As Range
Dim temp As Integer

ActiveSheet.Name = "Sheet1"

Set sht = ThisWorkbook.Sheets("Sheet1")
  
    LastRow = Range("A" & Rows.count).End(xlUp).Row
    With ActiveSheet
    .Cells(1, .Cells(2, .Columns.count).End(xlToLeft).Column + 1).Value = "Index"
    End With
    
    With ActiveSheet
    .Cells(2, .Cells(2, .Columns.count).End(xlToLeft).Column + 1).Formula = "SUM(LEN(LastColumn)-LEN(SUBSTITUTE(LastColumn,".jpg","")))/LEN(".jpg")"
    End With

The formula that I have looks at the last column with data, which contains multiple file names.我的公式查看最后一列的数据,其中包含多个文件名。 I'm trying to create an index on that column to tell me how many file names exist in this cell, as another part of my macro inserts rows based on this value.我正在尝试在该列上创建一个索引,以告诉我此单元格中存在多少个文件名,因为我的宏的另一部分基于此值插入行。 Any help would be appreciative.任何帮助将不胜感激。

Joe

Use R1C1 notation to refer to the column to the left of the column you are putting the formula in.使用 R1C1 表示法来引用要放入公式的列左侧的列。

With ActiveSheet
    .Cells(2, .Cells(2, .Columns.count).End(xlToLeft).Column + 1).Resize(LastRow - 1).FormulaR1C1 = "=SUM(LEN(RC[-1])-LEN(SUBSTITUTE(RC[-1],"".jpg"","""")))/LEN("".jpg"")"
End With

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

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