我有一個包含模板內容的 Word 檔案,我將在其中使用 vba 代碼將 Word 檔案中的文本框替換為我的用戶名,從而為每個用戶生成一個 pdf 報告。
在我打開Word檔案的excel檔案中的vba代碼中,我需要Word檔案的路徑。如果我對 Word 檔案路徑進行硬編碼,一切正常,沒有錯誤。但是,每當我嘗試將路徑存盤在 excel 單元格中并將其分配給變數時,都會導致錯誤 13 型別不匹配。
我已經將變數 coverLocation 調暗為 Variant 資料型別。我仔細檢查了路徑是否正確。
我試圖將它宣告為字串,但它會在我設定coverLocation的那一行給出另一個錯誤。錯誤是“需要物件”。
任何人都可以告訴我這樣做的正確方法是什么?太感謝了
下面是我的簡化代碼,只是為了顯示我在完整代碼中遇到的相同錯誤
Sub Test()
'Create and assign variables
Dim wb As Workbook
Dim ws1 As Worksheet
Dim saveLocation2 As String
Dim userName As Variant
Dim coverLocation As Variant
Set wb = ThisWorkbook
Set ws1 = wb.Worksheets("Sheet1")
Set userName = ws1.Range("B4")
Set coverLocation = ws1.Range("B2")
MsgBox coverLocation, vbOKOnly 'MsgBox showing correct path location
'Word variables
Dim wd As Word.Application
Dim doc As Word.Document
Set wd = New Word.Application
wd.Visible = True
saveLocation2 = wb.Path & Application.PathSeparator & userName & "cover.pdf"
'Word to PDF code
Set doc = wd.Documents.Open(coverLocation) ' "error 13 Type Mismatch" at this line
With doc.Shapes("Text Box Name").TextFrame.TextRange.Find
.Text = "<<name>>"
.Replacement.Text = userName
.Execute Replace:=wdReplaceAll
End With
doc.ExportAsFixedFormat OutputFileName:=saveLocation2, _
ExportFormat:=wdExportFormatPDF
Application.DisplayAlerts = False
doc.Close SaveChanges:=False
Application.DisplayAlerts = True
'Ending
wd.Quit
End Sub
uj5u.com熱心網友回復:
我將我的評論作為答案發布,以使其更具可讀性。問題是,在您的代碼coverLocation中是一個Range物件,而不是一個字串,對于userName.
解決此問題的最佳方法是替換此行:
Set coverLocation = ws1.Range("B2")`
有了這個:
coverLocation = ws1.Range("B2").Value
并另外替換
Dim coverLocation As Variant
為
Dim coverLocation As String
此外,您應該更換
Set userName = ws1.Range("B4")
和
userName = ws1.Range("B4").Value
在這種情況下,替換
Dim userName As Variant
為
Dim userName As String
也是可取的。
最終代碼可能如下所示:
Sub Test()
'Create and assign variables
Dim wb As Workbook
Dim ws1 As Worksheet
Dim saveLocation2 As String
Dim userName As String
Dim coverLocation As String
Set wb = ThisWorkbook
Set ws1 = wb.Worksheets("Sheet1")
userName = ws1.Range("B4").Value
coverLocation = ws1.Range("B2").Value
MsgBox coverLocation, vbOKOnly 'MsgBox showing correct path location
'Word variables
Dim wd As Word.Application
Dim doc As Word.Document
Set wd = New Word.Application
wd.Visible = True
saveLocation2 = wb.Path & Application.PathSeparator & userName & "cover.pdf"
'Word to PDF code
Set doc = wd.Documents.Open(coverLocation) ' "error 13 Type Mismatch" at this line
With doc.Shapes("Text Box Name").TextFrame.TextRange.Find
.Text = "<<name>>"
.Replacement.Text = userName
.Execute Replace:=wdReplaceAll
End With
doc.ExportAsFixedFormat OutputFileName:=saveLocation2, _
ExportFormat:=wdExportFormatPDF
Application.DisplayAlerts = False
doc.Close SaveChanges:=False
Application.DisplayAlerts = True
'Ending
wd.Quit
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/519618.html
標籤:擅长vba类型不匹配
