首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否有一种方法可以使用Excel将具有特定格式的文本添加到单元格中?

是否有一种方法可以使用Excel将具有特定格式的文本添加到单元格中?
EN

Stack Overflow用户
提问于 2022-06-23 19:49:34
回答 1查看 59关注 0票数 0

我正在处理一个宏,它将excel电子表格导出到csv,但是工作表中有格式单元格,我想通过将文本添加到它们应用到的单元格中来识别。对于顶部和左侧有边框的单元格,我想在单元格文本的开头添加一个“”。我已经能够让Cells.Replace使用只有顶部边框的空白单元格,但是没有任何其他格式被识别,而且它不适用于任何有内容的单元格,即使我试图完全替换内容。

以下是我到目前为止所得到的一个简化版本,我做错了什么?

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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问题的示例方法:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72735867

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档