早上好,我正在构建一个宏,它将从名为Committees的单元格A2表中找到某个文本,其中P2:CP5000的范围称为数据库,并返回A:O列中的所有相同行的数据包含此文本字符串的行,并从名为reports的工作表上的单元格F2开始打印出来。以下是我根据一些建议所做的工作。但是,它没有返回预期值,它将数据从数据库中的A列复制到报告中的F:T。此外,我认为循环不起作用,因为它在范围r1的最后一行之后不会停止。
Sub Macro1()
Dim r1 As Range, r2 As Range, r3 As Range
Dim rw1 As Long
Dim tmpRow As Long
tmpRow = 2
Set r2 = Sheets("Committees").Range("A2")
Set r1 = Sheets("Database").Range("P2:CO5000")
Set r3 = ThisWorkbook.Sheets("Reports").Range("F2:T2")
rw1 = 0
rw1 = r1.Find(What:=r2.Value, After:=r1(1)).Row
Do While rw1 <> 0
r3.Value = Sheets("Database").Range("A" & rw1 & ":O" & rw1).Value
tmpRow = tmpRow + 1
Set r3 = ThisWorkbook.Sheets("Reports").Range("F" & tmpRow & ":T" & tmpRow)
rw1 = 0
rw1 = r1.FindNext().Row
Loop
End Sub
提前致谢!
答案 0 :(得分:1)
最终修改:
我忘了检查是否已找到该特定单元格(现在使用FirstAddress)。无限循环是由于代码一遍又一遍地找到相同的条目。
我测试了以下代码,它对我有用。
Sub joseph()
Dim awb As Workbook
Dim cm, db, rp As Worksheet 'committees, database, reports
Dim tmpRng As Range
Dim firstAddress As String
Dim tmpRow As Integer
Dim r As Integer
Dim searchValue As String
Set awb = ThisWorkbook
With awb
Set cm = .Worksheets("Committees")
Set db = .Worksheets("Database")
Set rp = .Worksheets("Reports")
End With
searchValue = cm.Range("A2").Value
tmpRow = 0
r = 2
With db
Set tmpRng = .Range("P2:CP5000").Find(searchValue, _
LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext, MatchCase:=False)
If Not tmpRng Is Nothing Then
firstAddress = tmpRng.Address
Do
tmpRow = tmpRng.Row
rp.Range("F" & r & ":T" & r).Value = .Range("A" & tmpRow & ":O" & tmpRow).Value
r = r + 1
Set tmpRng = .Range("P2:CP5000").FindNext(tmpRng)
Loop While Not tmpRng Is Nothing And tmpRng.Address <> firstAddress
End If
End With
End Sub
初步回复和修改:
尝试更改此行
Set rw1 = .FindNext(rw1)
到
rw1 = r1.FindNext().Row
rw1不是范围,因此类型不匹配。如果有效,请告诉我。
修改:也改变这一行:
If Not rw1 Is Nothing Then
到
if rw1 <> 0 then
并添加此行
rw1 = 0
在此之前:
rw1 = r1.Find(What:=r2.Value, After:=r1(1)).Row
关于for循环和更新r3的Edit2: 如果文本字符串多次存在,则必须保留for循环,并且可以通过声明行变量来更新r3范围,例如:
Dim tmpRow = 2 as integer
然后在你的for循环中写入rw1 = 0
tmpRow = tmpRow + 1
set r3 = thisWorkbook.Sheets("Reports").Range("F" & tmprow & ":T" & tmprow)