[英]How to set a range using the find function
我有一个带有格式化单元格的样式化电子表格,供用户输入数据。 我正在尝试创建一个与按钮一起使用的宏,以一次清除所有输入单元格。 但是,我在“ find”和“ findformat”函数中苦苦挣扎。
为了简单起见,在这段代码中,我只是在寻找说“零售”的单元格。 当我运行代码时,即使电子表格中显然有一个单元格的值为“零售”,myRange的值也始终为Nothing。 有什么想法为什么范围什么都没有?
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/zh-CN/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
不当使用可能掩盖了其他错误,这些错误会对此功能的结果产生不利影响。 您可以像这样纠正后一个问题:
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
我只是不确定这种错误处理是否是解决问题的最佳方法,而且我也不明白为什么首先会发生错误。 因此,如果有人对此有任何想法,我将不胜感激。 如果没有,我很高兴它现在可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.