1

我有一个 VBA 脚本,旨在通过搜索 NBSPS,然后用常规空格替换它们,然后使用 trim 清理文本前后的空格,从 Microsoft Word 中的表格中去除不间断空格。就目前而言,该代码适用于除修剪表格中的第一个单元格之外的所有内容(但是,它确实替换了第一个单元格中的空格)。我希望找出 Word/VBA 是否有任何可能导致此问题的独特行为,因为我将为 MS Word 中的表格制作几个宏。

Sub nbsbCleanupQuick()
' use find and replace to replace all nbsp in the table with regular spaces
' use trim to clean up unwanted spaces
' For some reason this macro will replace nbsp with regular spaces but will not trim in the first cell of a table

' vars for counting
Dim numRows, numCells As Integer
Dim rindex, cindex As Integer

'container for cell contents
Dim container As String

Selection.Tables(1).Select
numRows = Selection.Rows.Count

For rindex = 1 To numRows
numCells = Selection.Tables(1).Rows(rindex).Cells.Count
For cindex = 1 To numCells
    container = ""
    Selection.Tables(1).Rows(rindex).Cells(cindex).Range.Select
    With Selection.Find
        .Text = Chr(160)
        .Replacement.Text = Chr(32)
        .Execute Replace:=wdReplaceAll, Wrap:=wdFindContinue
    End With
    If (Len(Selection.Text) - 2 > 0) Then
        container = Left(Selection.Text, Len(Selection.Text) - 2)
    End If
    Selection.Text = Trim(container)
Next
Next

End Sub

任何帮助,将不胜感激 :)

4

1 回答 1

1

因为您正处于更大项目的开始阶段,所以我会给您一些建议,对您的代码进行更多更改。请参阅下面提出的解决方案,其中包含一些解释代码内部更改原因的注释。显然,这解决了您在问题中描述的问题。

Sub nbsbCleanupQuick()
' use find and replace to replace all nbsp in the table with regular spaces
' use trim to clean up unwanted spaces
' For some reason this macro will replace nbsp with regular spaces but will not trim in the first cell of a table

' vars for counting
Dim numRows, numCells As Integer
Dim rindex, cindex As Integer

'container for cell contents
Dim container As String

Selection.Tables(1).Select
numRows = Selection.Rows.Count

'do replacement once, at the beginning
'it will be more efficient option
    ActiveDocument.Tables(1).Select
    With Selection.Find
        .Text = Chr(160)
        .Replacement.Text = Chr(32)
        .Execute Replace:=wdReplaceAll ', Wrap:=wdFindContinue
        'keep wrap parameter switch off to do replacement only within table 1
    End With

'to iterate through all cells in table use this kind of loop
Dim tblCell As Cell
For Each tblCell In ActiveDocument.Tables(1).Range.Cells

        'it's not necessary to select but I didn't want to
        'change your solution completly
        tblCell.Select

    'this check is easier to understand
    If (Len(Selection.Text) > 2) Then
        container = Left(Selection.Text, Len(Selection.Text) - 2)
    End If
    Selection.Text = Trim(container)

Next

End Sub
于 2013-08-30T15:36:34.873 回答