使用VBA计算名称的出现次数

对不起,我是VBA新手。 Vlookup要求X和Y列正常工作。 但是,对于列Z,我试图计算B列中的名称数量,但是一个错误不断popup。 我想知道为什么?

Dim lastrow As Long lastrow = Range("A2").End(xlDown).Row Range("X2:X" & lastrow).FormulaR1C1 = "=VLOOKUP(RC[-23],'Sheet2'!R1C1:R25000C10,7,0)" Range("Y2:Y" & lastrow).FormulaR1C1 = "=VLOOKUP(RC[-24],'Sheet2'!R1C1:R25000C10,2,0)" Range("Z2:Z" & lastrow).FormulaR1C1 = "=LEN(RC[-22]-LEN(SUBSTITUTE(RC[-22], "";"", ""))+1" Columns("X:Z").EntireColumn.AutoFit 

基本上,我试图达到如下。 Z列将自动填充B列中名称的出现

在这里输入图像说明

我认为你在你的函数string中缺less一个圆括号,以及空string的转义引号,所以它应该是:

  Range("Z2:Z" & lastrow).FormulaR1C1 = "=LEN(RC[-22])-LEN(SUBSTITUTE(RC[-22], "";"", """"))+1" 

我意识到这个答案不回答你的问题,但至less下面的代码服务于相同的目的。 为了解决这个问题,如果RGA先生指出范围内有空格或合并单元格,我改变了制定variablesLast_Row

  Sub Count_Name() Dim i As Long, Last_Row As Long With Sheets("Sheet1") 'It won't be a problem anymore if there are blanks or merged cells in the range using this line Last_Row = Range("A" & .Rows.Count).End(xlUp).Row For i = 2 To Last_Row If .Cells(i, "A") = "" Then .Cells(i, "B") = 0 Else .Cells(i, "B") = Len(.Cells(i, "A")) - Len(Replace(.Cells(i, "A"), ";", "")) + 1 End If Next i End With End Sub 

在这里我假设string名称在列A中 ,名称的数量在列B中 ,并且这两个数据都在Sheet1中 。 上面代码的等效Excel公式是

 =LEN(A2) - LEN(SUBSTITUTE(A2, ";", "")) + 1