我正在处理一个宏,它将excel电子表格导出到csv,但是工作表中有格式单元格,我想通过将文本添加到它们应用到的单元格中来识别。对于顶部和左侧有边框的单元格,我想在单元格文本的开头添加一个“”。我已经能够让Cells.Replace使用只有顶部边框的空白单元格,但是没有任何其他格式被识别,而且它不适用于任何有内容的单元格,即使我试图完全替换内容。
以下是我到目前为止所得到的一个简化版本,我做错了什么?
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.FindFormat.Clear
With Application.FindFormat.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
End With
With Application.FindFormat.Borders(xlEdgeTop)
.LineStyle = xlContinuous
End With
'Cells.Find(What:="", SearchFormat:=True).Select
Cells.Replace What:="*", Replacement:="||||", SearchFormat:=True
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub
发布于 2022-06-24 16:36:43
通常您在循环中使用Find()
与FindNext()
,但这似乎在使用SearchFormat:=True
时不起作用(参见http://www.tushar-mehta.com/publish_train/xl_vba_cases/1001%20range%20find.htm#_Using_the_SearchFormat:~:text=Unfortunately%2C%20FindNext%20does%20not%20respect%20the%20SearchFormat%20specification)
在添加前,您可能还需要检查单元格是否已经有一个前导“\”。
解决SearchFormat/FindNext问题的示例方法:
Sub SearchFormatExample()
Dim f As Range, addr, rng As Range
With Application.FindFormat
.Clear
.Borders(xlEdgeLeft).LineStyle = xlContinuous
.Borders(xlEdgeTop).LineStyle = xlContinuous
End With
Set rng = ActiveSheet.UsedRange
Set f = rng.Find("*", lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, LookIn:=xlFormulas, _
searchformat:=True)
If Not f Is Nothing Then addr = f.Address() 'note the first cell found
Do While Not f Is Nothing
Debug.Print f.Address
'don't add `|` if already present
If Not f.Value Like "|*" Then f.Value = "|" & f.Value
'using Find not findNext
Set f = rng.Find("*", after:=f, lookat:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, _
LookIn:=xlFormulas, searchformat:=True)
If f.Address = addr Then Exit Do 'exit when Find has looped back around
Loop
End Sub
https://stackoverflow.com/questions/72735867
复制相似问题