所以我在我的宏中有一个部分,我想添加我认为需要成为" Else"部分,但我对宏并不是很好,我正在寻求帮助。
Range("Z1").Copy
Dim FindString As String
Dim Rng As Range
FindString = Sheets("Pull").Range("Y1").Value
If Trim(FindString) <> "" Then
With Sheets("HourTracker").Range("A:A")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
Application.Goto Rng, True
Else
MsgBox "Nothing found"
End If
End With
ActiveCell.Offset(0, 1).Activate
Selection.PasteSpecial xlPasteValues
Application.DisplayAlerts = True
End If
End Sub
所以我想要这样做,而不是&#34; MsgBox&#34;没有找到&#34;&#34;,我希望它基本上执行与上面相同的操作,但复制单元格Z2,并在同一张表格中搜索Y2的值&#34; HourTracker&#34;然后粘贴该值。我不知道如何做到这一点,我的所有尝试都失败了。任何帮助将非常感激。如果您需要更多说明,请告诉我,提前谢谢!!!
答案 0 :(得分:0)
听起来像你在寻找一个循环。
Sub findStuff()
Application.DisplayAlerts = False
' The item you want to paste
Dim PasteString As String
' The item you're looking for
Dim FindString As String
' The range that may containing FindString
Dim Rng As Range
' The variable used to loop through your range
Dim iCounter as Long
' loop through the first cell in column Y to the last used cell
For iCounter = 1 To Sheets("Pull").Cells(Rows.Count, 25).End(xlUp).Row
' PasteString = the current cell in column Z
PasteString = Sheets("Pull").Cells(iCounter, 26).Value
' FindString = the current cell in column Y
FindString = Sheets("Pull").Cells(iCounter, 25).Value
If Trim(FindString) <> "" Then
With Sheets("HourTracker").Range("A:A")
' Find the cell containing FindString
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
' There's no need to activate/ select the cell.
' You can directly set the value with .Value
Rng.Offset(0, 1).Value = PasteString
Else
' Do nothing
End If
End With
Else
' Do nothing
End If
Next
Application.DisplayAlerts = True
End Sub
每次编译器点击Next
时,它都会在For
处重新开始,但会将iCounter
的值提高1.我们可以使用Cells
来完成此项Cells
1}}将行和列参数作为数字而不是字符串(如Range
)。语法只是Cells(Row #, Column #)
。因此,每当For . . . Next
再次循环时,iCounter
将逐一上升,您将在下一行搜索。
您可以使用.Paste
直接设置单元格的值,而不是使用.Value
。粘贴非常慢,使用.Value
要快得多。
Cells().End(xlUp).Row
是一种用于查找范围中最后使用过的单元格的方法。请参阅Error in finding last used cell in VBA,以获得比我在此处给出的更好的解释。