2013-04-29 142 views
1

我想在“Total Service Fees”单元格上面得到列G:26到1的总和。我遇到运行时错误'1004'。应用程序定义或对象定义的错误。有谁知道这可能来自什么?ActiveCell.Formula运行时错误1004

Worksheets(1).Select 
Dim rng1 As Range 
Dim strSearch As String 
strSearch = "Total Service Fees" 
Set rng1 = Range("F15:F100").Find(strSearch, , xlValues, xlWhole) 
If Not rng1 Is Nothing Then 
    rng1.Offset(0, 1).Select 
    ActiveCell.Formula = "=SUM(G26:" & ActiveCell.Offset(-1, 0).Select & ")" 
Else 
    MsgBox strSearch & " not found" 
End If 

我得到正确的答案,但我仍然得到这个错误。

+0

我不打算在该公式中使用“选择”方法。详细说明:打开立即窗口(CTRL + G)并输入 - 包括'?',然后按回车:??= SUM(G26:“&ActiveCell.Offset(-1,0).Select& )“'你应该看到这不是一个有效的公式。 – Gaffi 2013-04-29 19:42:27

+0

你会建议什么?它给我= SUM(G26:True) – Sokies 2013-04-29 19:45:01

+0

''SUM(G26:True)'是你告诉代码分配公式的代码。这是无效的,所以你需要提供一个有效的'A1'风格范围标识符。 – Gaffi 2013-04-29 19:48:03

回答

2

避免使用SELECT。您可能想要看到THIS

当您确定了具有搜索文本的单元格后,只需检索该单元格的行并使用该单元格即可。看到这个例子(UNTESTED)。

Dim rng1 As Range 
Dim strSearch As String 
Dim r As Long 

With Worksheets(1) 
    strSearch = "Total Service Fees" 
    Set rng1 = .Range("F15:F100").Find(strSearch, , xlValues, xlWhole) 
    If Not rng1 Is Nothing Then 
     r = rng1.Row 
     .Range("G" & r).Formula = "=SUM(G26:G" & r & ")" 
    Else 
     MsgBox strSearch & " not found" 
    End If 
End With 

注意:我没有做过任何错误处理。你将不得不照顾这一点。例如,如果在F26上找到搜索文字,该怎么办?

+0

这使得TotalServiceFees在执行SUM时包含一行 – Sokies 2013-04-29 19:50:18

+0

这就是你想要的吗? 'r = rng1.Row -1' – 2013-04-29 19:50:48

+0

如果你想在F单元格旁边的G单元格中找到文本,那么不要改变上面的公式。但是将'.Range(“G”&r).Formula =“= SUM(G26:G”&r&“)”'改为'.Range(“G”&r).Formula =“= SUM(G26: G“&(r-1)&”)“' – 2013-04-29 19:56:36

0
Set rng1 = Range("F15:F100").Find(strSearch, , xlValues, xlWhole) 

我认为你的问题在于此。尝试声明工作表或将变量设置为适当的工作表。

Dim WS as Worksheet 
Set WS = Activeworkbook.Sheets("Enter Sheet Name") 
Set rng1 = WS.Range("F15:F100").Find(strSearch, , xlValues, xlWhole)