Excel 在列中应用公式

Excel 在列中应用公式,excel,excel-formula,Excel,Excel Formula,我有一个公式来查找“NAME”列,在它后面添加一个空白列,并将这个新列命名为“wordcount”。现在我需要在新列中应用以下公式: =TRIM(LEN(E2)-LEN(替换(E2,“,”))+1 E列为“名称”列;但是,此列的位置可能因文件而异。请尝试下一个代码。它搜索列标题“NAME”在活动工作表的第一行中,并将引用找到的列的公式放置在找到的列后的第二列中: Sub ApplyFormula() Dim strColName As String, colRng As Range, la

我有一个公式来查找“NAME”列,在它后面添加一个空白列,并将这个新列命名为“wordcount”。现在我需要在新列中应用以下公式:

=TRIM(LEN(E2)-LEN(替换(E2,“,”))+1


E列为“名称”列;但是,此列的位置可能因文件而异。

请尝试下一个代码。它搜索列标题“NAME”在活动工作表的第一行中,并将引用找到的列的公式放置在找到的列后的第二列中:

Sub ApplyFormula()
   Dim strColName As String, colRng As Range, lastR As Long, colLetter As String
   strColName = "NAME" 'the header to search for
   'Supposing that the columns headers are in the first row:
    Set colRng = ActiveSheet.rows(1).Find(what:=strColName, LookIn:=xlValues, Lookat:=xlWhole)
   If Not colRng Is Nothing Then
        colLetter = Split(colRng.Address, "$")(1)
        lastR = cells(rows.count, colRng.Column).End(xlUp).row
        Range(colRng.Offset(1, 2), cells(lastR, colRng.Column + 2)).Formula = _
                       "=TRIM(LEN(" & colLetter & "2)-LEN(SUBSTITUTE(" & colLetter & lastR & ","" "","""")))+1"
    Else
        MsgBox "No """ & strColName & """ in the first row..." & vbCrLf & _
                   "Please, change the row (in the code) or search an existing header.", vbInformation, _
                   "No such column header..."
   End If
End Sub

请尝试下一个代码。它搜索列标题“NAME”在活动工作表的第一行中,并将引用找到的列的公式放置在找到的列后的第二列中:

Sub ApplyFormula()
   Dim strColName As String, colRng As Range, lastR As Long, colLetter As String
   strColName = "NAME" 'the header to search for
   'Supposing that the columns headers are in the first row:
    Set colRng = ActiveSheet.rows(1).Find(what:=strColName, LookIn:=xlValues, Lookat:=xlWhole)
   If Not colRng Is Nothing Then
        colLetter = Split(colRng.Address, "$")(1)
        lastR = cells(rows.count, colRng.Column).End(xlUp).row
        Range(colRng.Offset(1, 2), cells(lastR, colRng.Column + 2)).Formula = _
                       "=TRIM(LEN(" & colLetter & "2)-LEN(SUBSTITUTE(" & colLetter & lastR & ","" "","""")))+1"
    Else
        MsgBox "No """ & strColName & """ in the first row..." & vbCrLf & _
                   "Please, change the row (in the code) or search an existing header.", vbInformation, _
                   "No such column header..."
   End If
End Sub

它应该是好的,向我们展示代码“寻找列'名称'。。。你是说“C:C”列的“C”吗?现在,我假设您不想将上述公式应用于整个列。那么,根据哪一列计算要应用公式的最后一行?如果您能够定义范围,则无需任何迭代即可应用公式…最好向我们展示代码“查找列名称”。。。你是说“C:C”列的“C”吗?现在,我假设您不想将上述公式应用于整个列。那么,根据哪一列计算要应用公式的最后一行?如果您能够定义范围,则无需任何迭代即可应用公式。。。