第1个回答 2013-10-22
ALT+F11 打开VBE 窗口 粘贴代码 ,然后运行此宏
Sub 自动求和()
Dim c As Range
Dim findcells As Range
Dim rng As Range
Dim arr(1 To 65536)
Dim i, j, m As Integer
Set rng = Columns(1)
sr = "参考市值"
Set findcells = FindAll(SearchRange:=rng, FindWhat:=sr, _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False)
If Not findcells Is Nothing Then
For Each c In findcells
k = k + 1
arr(k) = c.Row
Next
End If
arr(k + 1) = [a65536].End(xlUp).Row + 2
For i = 1 To k
Range("a" & arr(i + 1) - 1).Font.ColorIndex = 3
Range("a" & arr(i + 1) - 1).Value = "=sum(a" & arr(i) + 1 & ":a" & arr(i + 1) - 2 & ")"
Next
End Sub
Function FindAll(SearchRange As Range, FindWhat As Variant, _
Optional LookIn As XlFindLookIn = xlValues, Optional LookAt As XlLookAt = xlWhole, _
Optional SearchOrder As XlSearchOrder = xlByRows, _
Optional MatchCase As Boolean = False) As Range
Dim FoundCell As Range
Dim FoundCells As Range
Dim LastCell As Range
Dim FirstAddr As String
With SearchRange
Set LastCell = .Cells(.Cells.Count)
End With
Set FoundCell = SearchRange.Find(what:=FindWhat, after:=LastCell, _
LookIn:=LookIn, LookAt:=LookAt, SearchOrder:=SearchOrder, MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
Set FoundCells = FoundCell
FirstAddr = FoundCell.Address
Do
Set FoundCells = Application.Union(FoundCells, FoundCell)
Set FoundCell = SearchRange.FindNext(after:=FoundCell)
Loop Until (FoundCell Is Nothing) Or (FoundCell.Address = FirstAddr)
End If
If FoundCells Is Nothing Then
Set FindAll = Nothing
Else
Set FindAll = FoundCells
End If
End Function本回答被提问者采纳