用于VBA的新行和COUNTIF函数

我正在计算(W_1)列中出现“1”的次数。 我在VBA上使用了以下代码(整个代码的一部分 – 如果需要,将添加更多)。 数据也是表格的一部分。

Private Sub Macro() LastRow = x.Sheets("W_10").Range("A" & Rows.Count).End(xlUp).Row Dim NewRow As Integer NewRow = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Row NewRow = LastRow + 1 ActiveSheet.Cells(NewRow, 2).Select ActiveCell.FormulaR1C1 = "=countif(@[W_1],1)" End Sub 

我不断收到以下错误

错误104 – 应用程序或对象定义的错误

有谁能让我知道我要去哪里错了吗? 我之前用过类似的公式,并且工作正常。

使用.Formula,而不是.FormulaR1C1并在列引用中包含表名

 Option Explicit Sub wqew() Dim NewRow As Long With ActiveSheet NewRow = 13 .Cells(NewRow, 2).Formula = "=countif(Table1[W_1], 1)" End With End Sub 

在这里输入图像说明

我没有你的示例数据来testing这个,但我编辑你的代码使用一些更明确的引用,这可能会带走你的错误…

 Private Sub Macro() Dim x As ActiveWorkbook Dim LastRow As Integer LastRow = x.Sheets("W_10").Range("A" & Rows.Count).End(xlUp).Row Dim NewRow As Integer NewRow = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Row NewRow = LastRow + 1 ActiveSheet.Cells(NewRow, 2).Select ActiveCell.FormulaR1C1 = Application.WorksheetFunction.CountIf([W_1], 1) End Sub 
 Sub FindingLastRow() 'PURPOSE: Different ways to find the last row number of a range 'SOURCE: www.TheSpreadsheetGuru.com Dim sht As Worksheet Dim LastRow As Long Set sht = ThisWorkbook.Worksheets("Update") 'Ctrl + Shift + End LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row sht.Cells(LastRow + 2, 2).Formula = "=countif(Resume[W_1],1)" End Sub 

这一个运气好运