【发布时间】:2015-12-28 17:50:57
【问题描述】:
我正在尝试编写一个 VBA 脚本来自动移动电子表格中的内容,该电子表格具有从会计软件导入的资产负债表。 导入的资产负债表上的值从第 5 行开始,A 列有一些文字描述每行的值的含义,B 和 D 列有每个项目的金额。
资产负债表的每个部分和子部分的小计位于 C 和 E 列。每个小计都位于一个带有实心上边框的单元格中。
我想将所有这些小计放在与值相同的列中(即 B 列和 D 列)。我尝试使用 .Find 方法搜索具有特定格式的单元格(具有上边框的单元格)并使用 Do 循环继续搜索,直到找到所有应该包含小计的单元格。
注意事项:
- 我没有使用 FindNext,因为它似乎忽略了前面 Find 方法中使用的格式设置,如 here 所述。
- 我尝试使用 FindAll function described by Tushar Mehta 来解决 FindNext 的这个问题,但它没有找到指定格式的所有单元格。
这是代码。非常感谢任何帮助!
Sub FixBalanceSheet()
Dim LookFor As Range
Dim FoundHere As String 'Address of the cell that should contain a subtotal
Dim beginAt As Range, endAt As Range, rng As Range 'Set the ranges for the sum to get the subtotal
Dim place As String 'String with the address of a cell that will contain a subtotal
Dim WhereToLook As Range 'Range where subtotals are to be found
'Set workbook and worksheet
With Sheets("Sheet1")
Set WhereToLook = Range("A5:F100")
'Every cell containing a subtotal has an upper border. So, look for cells containing border!
With Application.FindFormat.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
End With
'Call search using .Find
Set LookFor = WhereToLook.Find(What:="", After:=Cells(5, 2), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=True)
If Not LookFor Is Nothing Then 'Test if a cell with a bottom border is found
'What happens when a subtotal cell is found:
FoundHere = LookFor.Address
Debug.Print "Found at: " & Found
'Loop to set a range, sum values and put them in the right cell
Do
'% find out a range to calculate subtotals and put the value in the right cells %'
'Call for next search
With Application.FindFormat.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
End With
Set LookFor = WhereToLook.Find(What:="", After:=endAt, SearchFormat:=True)
Debug.Print "LookFor now is: " & LookFor.Address
Rem If LookFor.Address = Found Then ' Do not allow wrapped search
Rem Exit Do
Rem End If
Loop Until LookFor Is Nothing Or LookFor.Address = FoundHere ' Do not allow wrapped search
End If
End With
End Sub
【问题讨论】:
-
在随后的每次搜索中,您尚未将 endAt 重新分配为 LookFor...
-
Right Flephal,这就是他知道自己在终点/凝视点的方式。
-
感谢 Flephal,这就是导致无限循环的原因!
-
它没有找到所有有边框的单元格。
标签: vba excel find format infinite-loop