VBA使用旧Word文档的标题保存新创建的Excel工作表

时间:2016-05-23 09:08:40

标签: vba excel-vba excel

我可以使用方法

创建一个新的工作簿
workbooks.add 

但是,我需要使用与之前的Word文档相同的文件名保存它,我手动将所有有用的数据复制到其中。

我已经对此做了一些研究,并在VBA中发现了这个名为

的方法
saveas

但是每当我尝试时,它都无法保存与Word文档同名的新文件。

这是我的代码......

Dim wdFileName As Variant
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date  

Workbooks.Add


MyPath = "D:\Analysis\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

'this line below selects the word file to be chosen
MyFile = Dir(MyPath & "*.docx", vbNormal)

'If no files were found, exit the sub
If Len(MyFile) = 0 Then
    MsgBox "No files were found...", vbExclamation
    Exit Sub
End If

'Loop through each word file in the folder
Do While Len(MyFile) > 0

    'Assign the date/time of the current file to a variable
    LMD = FileDateTime(MyPath & MyFile)

    'If the date/time of the current file is greater than the latest
    'recorded date, assign its filename and date/time to variables
    If LMD > LatestDate Then
        LatestFile = MyFile
        LatestDate = LMD
    End If

    'Get the next word file from the folder
    MyFile = Dir
    Loop

 wdFileName = MyPath & LatestFile

(extra code here)
(extra code here)

ActiveWorkbook.SaveAs Filename:=wdFileName, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

(最后两行代码似乎根本没有任何效果,它不会保存Excel与我从中获取数据的Word文档相同的标题名称)

由于我还是VBA新手,所以非常感谢帮助!

请提供明确的代码以帮助我学习。

0 个答案:

没有答案