2014-01-22 80 views
0

我有一長串帳戶標籤,我需要將聯繫信息格式化爲只留下名稱(每段中的第一個單詞)。我對VBA excel有一些經驗,但這是我第一次進入Word。刪除每個段落中除第一個單詞外的所有內容

因此,我想要做的是刪除第一個單詞後面的所有內容,但如果可能的話保留所有段落的完整性(無論是誰將列表格式化爲大量中斷而不是間隔)。

感謝提前一噸!

回答

0

嘗試類似這樣的操作,根據需要進行修改。不是100%確定它會保留你的段落段落,但是這應該至少讓你在每個段落中的「第一個詞」列表。

Sub FirstWord() 
Dim myString$ 
Dim MyDoc As Document 
Dim DocPara As Paragraph 
Dim i% 
Dim p% 
Set MyDoc = ActiveDocument 

For p = MyDoc.Paragraphs.Count To 1 Step -1 
    Set DocPara = MyDoc.Paragraphs(p) 
    i = InStr(1, DocPara.Range.Text, " ") 
    DocPara.Range.Text = _ 
     Left(DocPara.Range.Text, i) & Right(DocPara.Range.Text, 1) 

Next 

End Sub 

修訂

爲了解決前導空格縮進每個段落,試試這個吧。我將修改上述例程,以便您可以看到對此代碼的一些更改以及我如何適應它。我還沒有測試過這個版本,讓我知道是否有任何問題。

Sub FirstWordIndented() 
Dim myString$ 
Dim x%    '<-- this is new 
Dim MyDoc As Document 
Dim DocPara As Paragraph 
Dim i% 
Dim p% 
Set MyDoc = ActiveDocument 

For p = MyDoc.Paragraphs.Count To 1 Step -1 
    Set DocPara = MyDoc.Paragraphs(p) 

    '// Make sure to ignore leading spaces 
    '// This block should remove leading spaces 
     myString = DocPara.Range.Text 
     Do 
      If Not Left(myString,1) = " " Then Exit Do 
      '// Removes the first character if it's a space 
      myString = Right(myString, Len(myString) - 1) 
     '// Loop until the first character isn't a space 
     Loop 

    '// Some small modifications to use the myString variable in this block: 
    i = InStr(1, myString, " ") 
    DocPara.Range.Text = _ 
     Left(myString, i) & Right(myString, 1) 

Next 

End Sub 

enter image description here

enter image description here

+0

它說的'DocPara.Range.Text = _ (左(無效的過程調用或參數DocPara.Range.Text,i - 1))&Right(DocPara.Range.Text,1)' – iboblaw

+0

嘗試'Left(DocPara.Range.Text,i)'? –

+0

現在它只是崩潰VBE和Word。幾秒鐘後「無響應」,無法恢復。 – iboblaw

相關問題