Vba 如何使用特定列的列名求和

Vba 如何使用特定列的列名求和,vba,Vba,我试图通过搜索工作表中可用的列名来对特定列求和,但如果我无法克服该错误,则会引发一些错误。有人能帮我解决这个问题吗 先谢谢你 Dim sh As Worksheet Dim Fnd As Range Dim c As Long Dim lr As Long Set sh = Sheets("Sheet1") Set Fnd = sh.Rows(1).Find("Basic", , xlValues, xlWhole) lr = Fnd.Ce

我试图通过搜索工作表中可用的列名来对特定列求和,但如果我无法克服该错误,则会引发一些错误。有人能帮我解决这个问题吗

先谢谢你

    Dim sh As Worksheet
    Dim Fnd As Range
    Dim c As Long
    Dim lr As Long
    Set sh = Sheets("Sheet1")
    Set Fnd = sh.Rows(1).Find("Basic", , xlValues, xlWhole)
    lr = Fnd.Cells(Fnd.Rows.Count, 1).End(xlUp).Row
    If Not Fnd Is Nothing Then
        Fnd.Cells(lr + 1, 0).Formula = "=SUM(" & Fnd.Range(Fnd.Cells(2, 0), Fnd.Cells(lr, 0)).Address & ")"
    Else
        MsgBox "Search Item Not Found!"
        Exit Sub
    End If
End Sub
这将解决这个问题:

Option Explicit
Sub Test()

    Dim RngToSum As Range, StrFind As String, ws As Worksheet, Col As Integer, LastRow As Long

    StrFind = "Basic"

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        Col = 0
        On Error Resume Next 'Error handler
        Col = .Cells.Find(StrFind).Column 'Find the column
        On Error GoTo 0
        If Not Col = 0 Then 'If the item is found
            LastRow = .Cells(.Rows.Count, Col).End(xlUp).Row 'the last row of that column
            Set RngToSum = .Range(.Cells(2, Col), .Cells(LastRow, Col)) 'Set the range
            .Cells(LastRow + 1, Col) = Application.Sum(RngToSum) 'sum the range on the next available row
        Else
            MsgBox "Search Item Not Found!"
        End If
    End With

End Sub

您的Fnd范围正是VBA找到Basic的单元格,因此您引用它的代码都会出错。我不知道你想做什么,但我看到你只需要找到列,结束和公式1c1==SUMR2C:R[-1]CI是这种编码语言的新手,我正试图找到一个基本的列名,并找到该特定列的和,而不知道列号。检查我的答案,如果它解决了你的问题。搞定了!谢谢你的帮助,Damain有帮助别忘了把它标记为答案,这样其他人可能会找到它。Damian,我还有一个疑问,那就是如何用负数计算那个总数,以及如何复制那个特殊的sumApplication。SumRngToSum*-1会做负数。根据复制值:.CellsLastRow+1,Col.copyNaild,它工作得很好,谢谢你的帮助,达曼