且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Excel VBA从Word文档复制数据

更新时间:2023-10-09 16:04:40

您可以使用以下函数:

Function GetData(StrDocNm As String, StrFnd As String)
'Note: A reference to the Word library must be set, via Tools|References
If StrDocNm = "" Then
  GetData = ""
  Exit Function
End If
If Dir(StrDocNm) = "" Then
  GetData = ""
  Exit Function
End If
Dim wdApp As New Word.Application, wdDoc As Word.Document
Set wdDoc = wdApp.Documents.Open(Filename:=StrDocNm, ReadOnly:=True, AddToRecentFiles:=False)
With wdDoc
  'process the documentWith ActiveDocument.Range
  With .Range
    With .Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Text = StrFnd & "*^13"
      .Replacement.Text = ""
      .Format = False
      .Forward = True
      .Wrap = wdFindStop
      .MatchWildcards = True
      .Execute
    End With
    If .Find.Found Then
      GetData = Trim(Split(Split(.Text, StrFnd)(1), vbCr)(0))
    Else
      GetData = ""
    End If
  End With
    'close
    .Close SaveChanges:=False
End With
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing
End Function

您将使用以下代码调用该代码:

which you'd call with code like:

Range("Z262").Value = GetData("C:\Users\" & Environ("UserName") & "\Documents\" & cmpNm.Text & ".doc", "String to Find")

上面的函数将返回在第一个段落中StrFnd变量之后的内容.请注意,查找"区分大小写.调用代码需要提供完整路径,文件名&扩展名(假设为".doc",但是您可能需要将其更改为".docx").

The above function will return whatever follows your StrFnd variable in the first paragraph in which it is found. Note that the Find is case-sensitive. The calling code needs to supply the full path, filename & extension (assumed to be ".doc", but you may need to change it to ".docx", for example).