vba - 从一个 Word 文档中选择部分文本并复制到另一个 Word 文档中
问题描述
我有一个带有一些空格的 word 文件,例如:
字文件XXXXXX
标题:XXXXX
ETC
我还有另一个 word 文件,其中缺少该数据:
字文件 20248
标题:word文件示例
ETC
我的问题是,如何使用 vba 识别第一个文件中的数据,以便将其复制到我想要的空间中的第二个文件中。此外,我希望您可以使用对话框选择所需的 word 文件,而不是输入文件所在的代码,因为我有不同的文件可以更改位置。
非常感谢您的回答。我在 vba 中很新,我从来没有在 word 上使用过它。
现在我有这个代码来选择我想从中复制数据的word文件:
Sub CopyData()
Dim DC As Document
Dim wD As Document, strD As String, wDNumb As Variant
Dim I As Long
Set wD = ActiveDocument
DSelection:
For I = 1 To Documents.Count
strD = strD & Documents(I).Name & " - " & I & vbCrLf
Next I
wDNumb = InputBox("Please, choose the number of the word file from which you are choosing the data to copy:" & vbCrLf & _
vbCrLf & strD, "Choose the word document from which you are copying the data!", 1)
If wDNumb <= Documents.Count And wDNumb >= 1 Then
GoTo DSelection2
ElseIf wDNumb = "" Then MsgBox "Operation cancelled", vbCritical, "Cancelled"
Exit Sub
ElseIf wDNumb > Documents.Count Or wDNumb < 1 Then MsgBox "Wrong number, input a correct number", vbExclamation, "Wrong number"
Exit Sub
End If
DSelection2:
If IsNumeric(wDNumb) Then
Set DC = Documents(CLng(wDNumb))
Else
MsgBox "Please choose the number on the right of the document chosen!": GoTo DSelection
End If
End Sub
我有以下代码部分,可以使用书签将 Word 的某些部分复制到另一个部分:
DC.Activate
Set Rng = DC.Range
With Rng.Find
.ClearFormatting
.Execute FindText:="TITLE:", Forward:=True, _
Format:=False, Wrap:=wdFindStop
Fnd = .Found
End With
If Fnd = True Then
With Rng
.MoveStart wdCharacter, 10
.MoveEnd wdSentence, 1
End With
End If
Rng.Select
Selection.Copy
wD.Activate
Selection.GoTo What:=wdGoToBookmark, Name:="TITLE"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Paste
解决方案
有多种可能的方法来解决这个问题,但您的问题描述缺乏足够的细节。例如,可以插入:
- 书签;
- 内容控制;
- 分节符;
- 表格;
- ETC。,
到目标文档中,以便可以在其中插入源文档中的内容。
或者,可以使用查找/替换来查找可以替换为所需内容的预定义字符串。
使用更新的问题描述,您可以使用:
Dim RngDC As Range, wDRng As Range, BkMkNm As String
BkMkNm "TITLE"
With DC
With .Range.Find
.ClearFormatting
.Execute FindText:=BkMkNm, Forward:=True, Format:=False, Wrap:=wdFindStop
End With
If .Found = True Then
.MoveStart wdCharacter, 10
.MoveEnd wdSentence, 1
Set RngDC = .Duplicate
End If
End With
With wD
Set wDRng = .Bookmarks(BkMkNm).Range
wDRng.FormattedText = RngDC.FormattedText
.Bookmarks.Add BkMkNm, wDRng
End With
推荐阅读
- typescript - 获取 CognitoIdentityCredentials 时的 RoleSessionName
- angular - Angular Material:mat-form-field 在创建自定义表单域控件时必须包含一个 MatFormFieldControl
- haskell - Haskell:无法导入 System.Random
- snowflake-cloud-data-platform - 直接使用外部表暂存 S3 文件
- c# - C# 的命令行代码没有按正确的顺序运行?
- spring - Spring Boot 条件 jpa 属性
- python - 在 pandas 数据框和回填中将年扩展到月
- leaflet - 使用 Leaflet 自动完成位置:自定义设计?
- c - 从 TLS TCP 套接字读取时收到乱码
- angular - 错误 TS2339:“对象”类型上不存在属性“funcionarios”