![](/img/trans.png)
[英]Opening word template and saving as .doc to current workbook folder - VBA in excel
[英]Opening Word Doc with VBA results in empty variable
我正在嘗試將 word 文檔的內容讀入 excel 中的任何單元格。 我已正確寫入文檔的文件路徑和文件名。 當我運行代碼時,我得到了一個變量,它的值為 'Nothing' 作為 word 文檔內容的值(變量名 = wdoc),但 word 文檔不是空文檔。
Sub readEmails()
Dim oFSO As Object, oFolder As Object, oFile As Object
Dim i As Integer
Dim sFileSmall As String, sFileYear As String, sFilePath As String
Dim wapp As Word.Application
Dim wdoc As Word.Document
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' USER INPUT
sFileSmall = "C:\Users\filesToRead\"
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
sFilePath = sFileSmall
' Get variable with filenames from folder (Only contains word docs)
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.getfolder(sFilePath)
i = 1
For Each oFile In oFolder.Files
'Sheet1.Cells(i, 5).Value = oFile.Name
Set wapp = GetObject(, "Word.Application")
If wapp Is Nothing Then
Set wapp = CreateObject("Word.Application")
End If
wapp.Visible = True
Set wdoc = wapp.Documents.Open(sFilePath & oFile) '<---- Error here. Assigns an empty variable
' Range("a1:a1") = wdoc.Content.Text
i = i + 1
Next oFile
End Sub
此錯誤是將不兼容的變量類型輸入Documents.Open()方法的結果。
Set wdoc = wapp.Documents.Open(sFilePath & oFile)
Documents.Open()方法需要一個文件名作為要輸入的字符串。 sFilePath聲明為字符串,而oFile聲明為對象。
在這種情況下,文件對象的.Name屬性會生成所需的字符串。 因此正確的代碼是:
Set wdoc = wapp.Documents.Open(sFilePath & oFile.Name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.