【发布时间】:2021-04-29 11:40:13
【问题描述】:
问题: 我有一些来自 word 的格式化文本,我想插入到 Excel 的一个单元格中。 我找不到完成这项工作的方法: 使用 PasteSpecial xlPasteAll 我在单元格中获得了一种图片 screen: xlPasteAll。 使用 PasteSpecial xlPasteValues 我得到了许多单元格中的文本,并且缺少某些文本的红色 screen: xlPasteValues with xlPasteFormats.
您有什么想法可以解决这个问题。我现在在论坛上搜索了几个小时,但没有成功。
Set oRng = WordDoc.Range
Set myrange = oRng.Duplicate
With myrange.Find
.Execute FindText:="Start*Next", matchwildcards:=True
savedTxt = Mid(myrange.Text, 6, Len(myrange.Text) - 9)
End With
myrange.Copy
Debug.Print myrange
With ActiveSheet.Range("E5")
'.PasteSpecial xlPasteAll
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
根据帮助进行了改进,但仍然粘贴在许多单元格上
Dim FileToOpen
Dim WordApp As Object
ChDrive "C:\"
DownloadsPath = Environ$("USERPROFILE") & "\Downloads"
ChDir DownloadsPath
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a file to import", _
FileFilter:="Word Files *.docx (*.docx),")
If FileToOpen = False Then
MsgBox "No file specified.", vbExclamation, "Error"
Exit Sub
Else
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
On Error Resume Next
'WordApp.Documents.Open Filename:=FileToOpen
Set WordDoc = WordApp.Documents.Open(FileToOpen)
End If
Set oRng = WordDoc.Range
Set myrange = oRng.Duplicate
'set start position to "project description" -> jump over table of contents
' orng.Find.Execute(findtext:="Project Description", matchwildcards:=True) 'returns True
StartDescription = InStr(1, oRng, "Project description", vbTextCompare)
colPrj = 1
nrow = 1
Set oRng = WordDoc.Range
Set oRng = wdApp.Application.ActiveDocument.Range(Start:=StartDescription, End:=0)
Dim nexti As Long
Dim pos As Long
Dim fend As Boolean
fend = False
Do While Not IsEmpty(Cells(nrow, colPrj).Value)
prjName = Cells(nrow, colPrj)
Position = InStr(1, myrange, prjName, vbTextCompare)
'find Position: start of the Project Name
If Position > 0 Then
'next steps area is until next Project Name
With oRng.Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = False
.Forward = True
.Wrap = wdFindStop
.MatchWildcards = True
.Text = "Next Steps*Project Name: "
.Execute
If .found = True Then
.Start = .Start + 11
.End = .End - 14
With .Duplicate.Find
.Wrap = wdFindStop
.MatchWildcards = True
.Text = "[^13^l]"
.Replacement.Text = "¶"
.Execute Replace:=wdReplaceAll
.Text = "^t"
.Replacement.Text = "§"
.Execute Replace:=wdReplaceAll
End With
oRng.Copy
With ActiveSheet
.Paste Destination:=.Range("C" & nrow)
With .Range("C" & nrow)
For i = 1 To Len(.Text)
With .Characters(i, 1)
If .Text = "¶" Then .Text = Chr(10)
If .Text = "§" Then .Text = vbTab
End With
Next
End With
End With
End If
End With
End If
nrow = nrow + 1
Loop
WordApp.Quit
Set WordApp = Nothing
Set WordDoc = Nothing
直接分配比使用 .PasteSpecial 获得更好的结果, 但后来我失去了所有格式。 范围(“E5”)=我的范围
【问题讨论】:
-
word 中的文本是否在文档中特定或唯一的位置,例如书签、表格等?
-
不,它最初是从 Excel 单元格复制到 Word 报告中。在那里它被修改了。带有颜色和回车。现在我想把它写回来。