背景:我创建了一个仪表板,它有一个 VBA 按钮,可以将文本从单元格复制到剪贴板,这样我就可以将文本(这是一个模板)粘贴到我的工作管理系统中。由于更新,我现在可以将格式化的文本传递到我的工作系统中。不幸的是,如果我只是复制单元格中的文本,它会在粘贴时丢失其格式(即单元格中的文本是bold并且我复制它,文本将粘贴无格式)。我发现如果我从 word 文档复制并粘贴到我的工作系统中,格式将被保留。
我需要一种方法来单击按钮并告诉 excel 从嵌入的 word 文档“对象 1”中复制文本。
由于我的工作管理系统,嵌入的 word 文档是我复制模板及其要点并在粘贴时正确格式化的唯一方法。
在下面的示例中,嵌入的 word 文档是电子表格中的对象 1,并在论坛栏中列为 =EMBED("Word.Document.12","")。
Private Sub CommandButton1_Click()
Dim objWord As Object
Dim objDoc As Object
Dim strText As String
'Get the Word application object
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
End If
On Error GoTo 0
'Select the Word document
Set objDoc = objWord.ActiveDocument.Shapes("object 1").OLEFormat.Object
If objDoc Is Nothing Then
MsgBox "The embedded Word document 'word1' was not found."
Exit Sub
End If
'Copy the text to the clipboard
strText = objDoc.Content.Text
If strText <> "" Then
Clipboard.SetText strText
End If
'Clean up
Set objDoc = Nothing
Set objWord = Nothing
End Sub
编辑-这样更好。当你想把文档内容放到剪贴板上时调用sub
Sub CopyWordText()
Dim WDO As OLEObject, WdDoc As Object
Set WDO = ActiveSheet.OLEObjects("object 1")
Application.ScreenUpdating = False
WDO.Verb xlVerbPrimary 'activate the embedded file
WDO.Object.Range.Copy
Range("A1").Select 'deactivate the embedded file
End Sub