VBA saveas newly created Excel sheet using old Word Document's title

General Tech Learning Aids/Tools 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Learning Aids/Tools related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

 

I can create a new workbook by using the method

workbooks.add 

However, I need to save it with the same file name as the previous Word document which I manually copied all the useful data into it.

I have done some research into this and have found out about this method in VBA called

saveas

but whenever I try, it fails to save the new file with the same name as the Word document.

This was my code...

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

(the last 2 lines of code do not seem to have any effect at all and it does not save the Excel with the same title name as the Word document I get my data from)

As I'm still new in VBA, help would be much appreciated with thanks!

Please do provide clear code to aid in my learning.

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.