2013-10-15 20 views
2

我需要做的是搜索一個單詞文件的一美元金額,然後將金額返回到用戶驗證程序。我知道金額以「$」開頭,並以小數點後兩位數字結尾(每個文檔只有一個金額)。搜索如我所願返回真實,但我怎樣才能真正從word文檔中提取完整數字(將被分配給一個變量)使用通配符在doc中查找字符串;返回完整的字符串VBA

下面的代碼(Excel 2010);乾杯。

With wdDoc.Content.Find 
    .Text = "$*.??" 
    .MatchWildcards = True 
    If .Execute Then 
     'would be verified here 
    Else 
     'etc 
    End If 
End With 

編輯: 我設法得到以下工作;

With wdApp.Selection.Find 
     .Text = "$*.??" 
     .Wrap = wdFindAsk 
     .Forward = True 
     .MatchWildcards = True 
     If .Execute Then 
     debug.print wdApp.Selection.Text 
     Else 
     debug.print "Not Found" 
     End If 
    End With 

唯一的負面情況是,如果用戶管理的選擇,而這種搜索運行不同的word文檔,也不會因爲選擇已經改變找到的結果。是否有任何方法專門搜索代碼中前面打開的活動文檔? ( 「wdDoc」)。使用wdDoc.Content似乎沒有任何方式返回字符串。

編輯2:有沒有辦法使用Word.Document而不是Word.Application從搜索中返回文本?

回答

1

可以使用Range對象引用找到的文本。

另外,Find模式$*.??可以在您的文檔中找到很多內容,除了您想要的以外,如果有迷路$存在。

您可以使用此模式來查找準確美元金額

$[0-9]{1,}.[0-9]{2} 

Sub Demo() 
    Dim wdDoc As Document 
    Dim oRng As Range 

    ' Set reference to required doc 
    Set wdDoc = ActiveDocument 

    ' .... 

    Set oRng = wdDoc.Content 
    With oRng.Find 
     .Text = "$[0-9]{1,}.[0-9]{2}" 
     .Wrap = wdFindAsk 
     .Forward = True 
     .MatchWildcards = True 

     If .Execute Then 
      Debug.Print oRng 
     Else 
      'etc 
     End If 
    End With 
End Sub 
1

試試這個

With ActiveDocument.Content.Find 
    .Text = "$*.??" 
    .Replacement.Text = "" 
    .Forward = True 
    .Wrap = wdFindAsk 
    .MatchWildcards = True 
    If .Execute Then 
     Debug.Print Selection.Range.Text 
    Else 
     Debug.Print "not Found" 
    End If 
End With 

隨訪

試試這個(久經考驗的)

Sub Sample() 
    ActiveDocument.Content.Select 
    With Selection.Find 
     .Text = "$*.??" 
     .Replacement.Text = "" 
     .Forward = True 
     .Wrap = wdFindContinue 
     .MatchWildcards = True 
     If .Execute Then 
      Debug.Print Selection.Range.Text 
     Else 
      Debug.Print "not Found" 
     End If 
    End With 
End Sub 
+1

使用Selection.Range.Text給出錯誤「450:參數或無效的屬性賦值錯誤號碼」 –

+0

見更新後 –

相關問題