简体   繁体   中英

ActiveCell.Formula Run-time error 1004

I am trying to get the sum of columns G:26 to 1 above the "Total Service Fees" cell. I am running into a Run-time error '1004'. Application-defined or object-defined error. Does anyone know what this could be from?

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

I get the right answer, but I still get this error.

Avoid the use of SELECT . You may want to see THIS

When you have identified the cell which had the search text then simply retrieve the row of that cell and use that. See this example (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

Note : I have not done any error handling. You will have to take care of that. For example, what if the search text if found on F26 ?

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

I think your problem lies here. Try declaring the worksheet or setting a variable to the appropriate sheet.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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