我试图通过搜索工作表中可用的列名称来求和特定的列,但是如果我无法克服该错误,则会抛出一些错误。有人可以帮我吗
提前谢谢
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
答案 0 :(得分:0)
这可以解决它:
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