Hi,

How to open a excel file from word macro by getting the file name from word.
this is my code

OrgFileName = Selection.Text + ".xls"
'OpenExcel Macro
Shell ("C:\Program Files\Microsoft Office\OFFICE11\excel ""C:\My Documents\File - CopyBook\""" + OrgFileName)

OrgFileName is the workbook name which i have to get from word document

Thanks
Kalpana :-)

Dani AI

Generated

used Selection.Text to build a workbook name and launched Excel with Shell. That will work in simple cases but is brittle: the selection often contains a trailing paragraph mark, file extensions vary (.xls, .xlsx, .xlsm), and hard-coded Office paths (OFFICE11) break on other machines or Office versions. A safer pattern is to (1) clean the selected text, (2) build a full file path (or use ThisDocument.Path if the workbook sits beside the Word file), (3) confirm the file exists, and (4) automate Excel via GetObject/CreateObject and Workbooks.Open. This avoids quoting problems and dependence on a specific excel.exe location.

A compact, practical VBA workflow (sanitise selection, check file, open in Excel):

Sub OpenSelectedExcel()
    Dim selText As String, fileName As String, filePath As String, xlApp As Object

    selText = Trim(Replace(Selection.Range.Text, vbCr, ""))
    If selText = "" Then Exit Sub

    fileName = selText
    If InStrRev(fileName, ".") = 0 Then fileName = fileName & ".xlsx"  ' adjust extension if needed

    filePath = ThisDocument.Path & "\" & fileName
    If Dir(filePath) = "" Then
        MsgBox "File not found: " & filePath, vbExclamation
        Exit Sub
    End If

    On Error Resume Next
    Set xlApp = GetObject(, "Excel.Application")
    If Err.Number <> 0 Then
        Err.Clear
        Set xlApp = CreateObject("Excel.Application")
    End If
    On Error GoTo 0

    xlApp.Visible = True
    xlApp.Workbooks.Open filePath
End Sub

Troubleshooting notes: remove paragraph marks from the selection (use Replace as shown), choose the correct extension for the target workbook, and use Dir to verify existence before opening. For automation details see the official docs for Workbooks.Open (Excel VBA) and the GetObject function (VBA). Thanks to for the attachment earlier in the thread.

Recommended Answers

All 3 Replies

Plz check out the following attached file.

Hi Shaik,
Thanks for your help.

Regards,
Kalpana

Plz mark the thread as solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.