我有一个带有格式化单元格的程式化电子表格,供用户输入数据。我正在尝试使用按钮创建一个宏来同时清除所有输入单元格。但是,我正在努力寻找"发现"和" findformat"功能
为了简单起见,在这段代码中我只是寻找说" Retail"的单元格。当我运行代码时,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
答案 0 :(得分:1)
我参考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
注意:分配到范围对象Set
时,您应该使用myRange
关键字。此外,您对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
答案 1 :(得分:0)
我按如下方式更改了我的代码,现在它的工作方式完全符合我的要求:
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
我只是不确定这种错误处理是否是处理问题的最佳方法,我不明白为什么首先会发生错误。所以,如果有人对此有所考虑,我将不胜感激。如果没有,我现在很开心它。