我需要在一個 excel 報告中插入一個 QR 碼,其中源資料也在這個 excel 上。由于我公司的政策,我不能使用任何外部鏈接或應用程式,所以谷歌圖表、二維碼 API 等不是一個選項......我的想法是,從 excel 報告中呼叫創建一個 MS Word 檔案,添加一個欄位并使用 {DISPLAYBARCODE...} 控制欄位,生成我的二維碼,以圖片形式回傳到我的 Excel 報告中。MS Word 將在不保存的情況下關閉。
我不是 VBA 大師,我不知道我的代碼不起作用。我可以創建一個打開的 MS Word 檔案,粘貼一個簡單的文本,但我無法創建該欄位,總是有錯誤 450 訊息。
Sub CopyToWord()
Dim doc As Object 'Word.Document
Set doc = CreateObject("Word.Document") 'New Word.Document
doc.Application.Visible = False 'Leave the Word document visible
With doc.ActiveWindow.Selection
doc.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="DISPLAYBARCODE xxx", PreserveFormatting:=True
.Fields.ToggleShowCodes
End With
doc.Application.Activate
End Sub
uj5u.com熱心網友回復:
在跨 Office 應用程式作業時,正確限定每個物件至關重要。例如:Selection.Range可以指 Word 或 Excel。由于代碼是從 Excel 中運行的,因此對不合格的參考Selection將被解釋為含義Excel.Selection。
作為您Selection的孩子,Application您還需要在代碼中包含一個應用程式物件。
Public Function GetWordApp(wdApp As Object) As Boolean
On Error Resume Next
GetWordApp = False
Set wdApp = GetObject(, "Word.Application")
If Err > 0 Or wdApp Is Nothing Then
'Word not yet open
Err.Clear
Set wdApp = CreateObject("Word.Application")
If Err = 0 Then GetWordApp = True
Else
GetWordApp = True
End If
On Error GoTo 0
End Function
Sub CopyToWord()
Dim wdApp As Word.Application, doc As Word.Document, fld As Word.Field
If GetWordApp(wdApp) Then
Set doc = wdApp.Documents.Add
'use this if you want to do something else with the field
Set fld = doc.Fields.Add(Range:=wdApp.Selection.Range, Type:=wdFieldEmpty, Text:="DISPLAYBARCODE xxx", PreserveFormatting:=True)
fld.ShowCodes = True
'alternative method
'doc.Fields.Add Range:=wdApp.Selection.Range, Type:=wdFieldEmpty, Text:="DISPLAYBARCODE xxx", PreserveFormatting:=True
'doc.Range.Fields.ToggleShowCodes
wdApp.Visible = True
wdApp.Activate
End If
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528694.html
上一篇:在Access中,除非表單已經臟,否則系結的組合框不會更新
下一篇:使用Excel值
