我是一家公司的实习生,他们做了大量的DCR和电感读数,并拥有文本文件的所有值。我设法使用VBA将这些文本文件导入excel电子表格,但现在我需要开始操作该数据。我正在尝试编写一些代码,它将循环遍历整个列并搜索字符串“** DCR”,然后给我单元格偏移量(1,3)中的数据,复制,然后将其粘贴到同一工作簿中的不同范围。我编写了代码来搜索字符串的第一个实例,然后将我需要的数据复制并粘贴到范围中,然后它就会停在那里。我写的Do循环代码给了我一个无限循环而且不起作用。到目前为止,这是我的代码。
Sub Button2_Click()
Dim rng1 As Range
Dim strSearch As String
strSearch = "**DCR"
Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
If Not rng1 Is Nothing Then
rng1.Offset(1, 3).Copy
Range("N11").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("O11").Select
Do
Set rng1 = Range("A:A").FindNext(rng1)
Loop
End If
End Sub
任何人都可以告诉我我错过了什么和/或做错了什么。非常感谢你!
答案 0 :(得分:0)
试试这个......
Sub Button2_Click()
Const DCR As String = "**DCR"
Dim rngSearch As Range
Set rngSearch = ActiveSheet.Range("A:A")
Dim rngFoundFirst As Range
Set rngFoundFirst = rngSearch.Find(DCR, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True)
' Anything found?
If Not rngFoundFirst Is Nothing Then
Call ProcessDcr(rngFoundFirst)
Dim rngFoundNext As Range
Set rngFoundNext = rngFoundFirst
Do
Set rngFoundNext = rngSearch.FindNext(rngFoundNext)
' If first one is found, stop looping.
If Not rngFoundNext Is Nothing Then
If rngFoundNext.Address = rngFoundFirst.Address Then
Exit Do
End If
Call ProcessDcr(rngFoundNext)
End If
Loop Until rngFoundNext Is Nothing
End If
Set rngFoundNext = Nothing
Set rngFoundFirst = Nothing
Set rngSearch = Nothing
End Sub
Sub ProcessDcr(rngFound As Range)
Call rngFound.Offset(1, 3).Copy
Call Range("N11").PasteSpecial(Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False)
End Sub
答案 1 :(得分:0)
你需要移动Do-Loop:只要找到结果就基本循环,当没有找到结果时退出。但代码仍会循环,导致findNext将继续查找下一个结果,即使它已经找到它。所以你必须继续跟踪你的第一个结果。
您可能希望增加复制的位置。
请记住,复制和粘贴在Excel中很昂贵,更好更快的方法是复制单元格值。
Dim strSearch As String Dim rng1 As Excel.Range Dim firstrng1 As Excel.Range Dim rowNumber as Integer rowNumber = 11; strSearch = "**DCR" Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole) If rng1 Is Nothing Then Exit Sub Set firstrng1 = rng1 Do Range("N" & rowNumber).Value = rng1.Offset(1, 3) rowNumber = rowNumber + 1 Set rng1 = Range("A:A").FindNext(rng1) If rng1.Address = firstrng1.Address Then Exit Do Loop