如何使用查找function设置范围

我有格式化单元格的程式化的电子表格供用户input数据。 我正在尝试创build一个macros用于一个button清除所有的input单元一次。 但是,我正在努力寻找和查找格式函数。

为了简单起见,在这个代码中,我只是在寻找一些说“零售”的单元。 当我运行代码时,myRange的值始终为Nothing,即使电子表格中有一个值为“Retail”的单元格。 任何想法,为什么范围是什么?

Public Sub reset() 'reset all input fields to no value msg = MsgBox("Are you sure you want to delete all data and reset all files to original state?", vbYesNoCancel, "***Warning***") If msg = vbYes Then Dim inputCell As Long Dim noteCell As Long inputCell = RGB(255, 204, 153) noteCell = RGB(255, 255, 204) Dim myRange As Range Dim mySheet As Worksheet Dim shp As Shape Dim sht As Worksheet Dim objXL As Object Dim wb As Workbook Dim pathName, name, myLink As String Set sht = ActiveSheet Set wb = ActiveWorkbook pathName = wb.FullName name = wb.name For Each shp In sht.Shapes If shp.Type = msoGroup Then For i = 1 To shp.GroupItems.Count If shp.GroupItems(i).Type = msoEmbeddedOLEObject Then shp.GroupItems(i).Select shp.GroupItems(i).OLEFormat.Activate Set wb = ActiveWorkbook If Not IsEmpty(wb.LinkSources(xlExcelLinks)) Then For Each link In wb.LinkSources(xlExcelLinks) On Error Resume Next wb.ChangeLink name:=link, newName:=pathName, Type:=xlLinkTypeExcelLinks Next link End If For Each mySheet In ActiveWorkbook.Worksheets With Application.FindFormat.Interior.Color = inputCell myRange = mySheet.Cells.Find(what:="Retail") ', searchformat:=True) myRange.ClearContents End With Next mySheet wb.Close (False) End If Next i End If Next shp End If End Sub 

例如,我参考了FindFormat文档:

https://msdn.microsoft.com/en-us/library/office/ff838023.aspx

然后修改你的代码:

 With Application.FindFormat .Interior.Color = inputCell Do Set myRange = mySheet.Cells.Find(what:="Retail", SearchFormat:=True) If myRange Is Nothing Then myRange.ClearContents Loop While Not myRange Is Nothing End With 

注意 :分配给范围对象myRange时,应该使用Set关键字。 此外,您错误地使用On Error Resume Next可能会掩盖额外的错误,这些错误会对此function的结果产生负面影响。 你可以这样纠正后面的问题:

  If Not IsEmpty(wb.LinkSources(xlExcelLinks)) Then For Each link In wb.LinkSources(xlExcelLinks) On Error Resume Next wb.ChangeLink name:=link, newName:=pathName, Type:=xlLinkTypeExcelLinks On Error GoTo 0 '### RESUME NORMAL ERROR HANDLING Next link End If 

我改变了我的代码如下,现在它工作正如我想:

  For Each mySheet In ActiveWorkbook.Worksheets With Application.FindFormat .Interior.Color = inputCell Do On Error GoTo handler: Set myRange = mySheet.Cells.Find(what:="?*", searchformat:=True).MergeArea If Not (myRange Is Nothing) Then myRange.ClearContents End If Loop While Not (myRange Is Nothing) .Interior.Color = noteCell Do On Error GoTo handler: Set myRange = mySheet.Cells.Find(what:="?*", searchformat:=True).MergeArea If Not (myRange Is Nothing) Then myRange.ClearContents End If Loop While Not (myRange Is Nothing) handler: Set myRange = Nothing Resume Next End With Next mySheet 

我只是不确定这样的error handling是否是处理这个问题的最好方法,我不明白为什么一个错误发生在第一位。 所以如果有人有这个想法,我将不胜感激。 如果不是的话,我现在只是开心而已。