简体   繁体   English

使用 VBA 打开 Word Doc 导致空变量

[英]Opening Word Doc with VBA results in empty variable

I am trying to read the contents of a word document into any cell in excel.我正在尝试将 word 文档的内容读入 excel 中的任何单元格。 I have the filepath and filename of the document correctly written.我已正确写入文档的文件路径和文件名。 When I run the code, I get a variable with 'Nothing' as the value for the contents of the word document (variable name = wdoc), but the word document is not an empty document.当我运行代码时,我得到了一个变量,它的值为 '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

This error is the result of inputting an incompatible variable type into the Documents.Open() method.此错误是将不兼容的变量类型输入Documents.Open()方法的结果。

Set wdoc = wapp.Documents.Open(sFilePath & oFile) 

The Documents.Open() method requires a filename as a string to be input. Documents.Open()方法需要一个文件名作为要输入的字符串。 While sFilePath is declared as a string, oFile is declared as an object. sFilePath声明为字符串,而oFile声明为对象。

In this case the .Name property of the File-object produces the desired string.在这种情况下,文件对象的.Name属性会生成所需的字符串。 Thus the correct code is:因此正确的代码是:

 Set wdoc = wapp.Documents.Open(sFilePath & oFile.Name) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM