我正在尝试从每个工作表中查找"HFM",如果有一个粘贴之后的一些名称。那么问题是如何避免在工作表中没有"HFM"时将名称添加到工作表中?
我首先有没有错误恢复的代码下一个,但随后出现运行时错误。添加时,它会将名称复制到所有工作表。此外,如果从没有"HFM"的工作表启动,它会返回运行时错误。那么我该如何解决这个问题呢?
Dim ws As Worksheet
For Each ws In Worksheets
Cells.Find(What:="HFM", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False).Activate
On Error Resume Next
ActiveCell.Offset(0, 3).Select
ActiveCell.FormulaR1C1 = "name1"
' etc.
而不是"出错时恢复下一步",您必须根据结果声明一个变量继续。下面是一个示例。
Dim ws As Worksheet
For Each ws In Worksheets
' Search for a text
Set MyObjectvie = ws.Cells.Find(What:="HFM", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False)
If Not MyObjectvie Is Nothing Then
' if the text is found do the task
MyObjectvie.Offset(0, 3).Value = "name1"
End If
Next ws