Link to home
Start Free TrialLog in
Avatar of tantormedia
tantormediaFlag for United States of America

asked on

Opening .txt document in MS Word programmatically

Dear experts,

I need to open a text file in MS Word programmatically.
When I use
ShellExecute(NULL, "open", "Winword.exe", pSheet->m_strDestinationFilePath, NULL, SW_SHOWNORMAL);
I get error messages, first "The file could not be found. (C:\Documents.doc) (I have no idea where this path comes from), then "The file could not be found. (C:\Documents and Settings\...\and.doc - don't know this one either), then "The directory name is not valid. (C:\Documents and Settings\...\myTextFile.txt).
If I use "notepad.exe" instead of "Winword.exe", the file opens correctly in Notepad.
What am I doing wrong?
Thanks.
Avatar of GeoffHarper
GeoffHarper
Flag of United States of America image

Try:

     ShellExecute(NULL, "open", "Winword.exe", """" & pSheet->m_strDestinationFilePath & """", NULL, SW_SHOWNORMAL);
ASKER CERTIFIED SOLUTION
Avatar of GeoffHarper
GeoffHarper
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tantormedia

ASKER

Thank you very much! It worked, though I still have some problems. Before opening the file, I get a "File in Use" message: "myfile.txt is locked for editing by 'another user'. Do you want to:
- Open a Read Only copy
- Create a local copy and merge you changes later
- Receive notification when the original copy is available.
I didn't have this with notepad. Is it possible to avoid this error? I don't want a read only copy, I want to be able to edit the file.
After I pick e.g. the first option, I have a file conversion dialog:
Select the encoding that makes your document readable: Windows(default), MS DOS, Other encoding.
Is it possible to automatically make it Windows without seeing this dialog?
Thanks.
There are various command line switches for MS Word but none will convert a .txt file for you automatically (I don't think).

Make sure you don't actually have the file open elsewhere when you run your program.  Check in Task Manager for another instance of your program which may not have terminated, leaving the file still open.
Thank you very much.