首页 > 解决方案 > 删除“-”字之前的所有字符

问题描述

我有一个包含许多不同名称的大型 Word 文档,例如:

Joe Bloggs Ltd - Joe Bloggs Limited Acc
Adam Smith Ltd - Adam Smith Limited Acc

都在表格中,在单独的单元格中。

我想知道 word 中的 VBA 代码会得到这样的输出:

Joe Bloggs Limited Acc
Adam Smith Limited Acc

而不是每次手动删除“-”之前的部分。

任何帮助将非常感激。

编辑:

到目前为止,我有这个不起作用:

Sub replaceCharToNothing()
Dim itable As Table
Dim C As Cell
Dim str1 As String
For Each itable In ThisDocument.Tables
    For Each C In itable.Range.Cells
        C.Range.Text = Left(str1, InStr(str1, "-") - 1)
    Next
Next
End Sub

编辑 2.0

我现在有有效的代码:

Dim myTable As Table
Dim myrow As Row
Dim i As Integer
Dim x As Integer

For Each myTable In ActiveDocument.Tables
    For Each myrow In myTable.Rows
        For i = 1 To myrow.Cells.Count
                x = InStr(myrow.Cells(i).Range.Text, "-")
            If x > 0 Then
                    myrow.Cells(i).Range = Replace(Trim(Mid(myrow.Cells(i).Range.Text, x + 1)), ChrW(13), "")
            End If
        Next i
    Next myrow
Next myTable

标签: vbams-word

解决方案


Dim myTable As Table
Dim myrow As Row
Dim i As Integer
Dim x As Integer

For Each myTable In ActiveDocument.Tables
    For Each myrow In myTable.Rows
        For i = 1 To myrow.Cells.Count
            x = InStr(myrow.Cells(i).Range.Text, "-")
            If x > 0 Then
                myrow.Cells(i).Range = Replace(Trim(Mid(myrow.Cells(i).Range.Text, x + 1)), ChrW(13), "")
            End If
        Next i
    Next myrow
Next myTable

推荐阅读