I need VBA code that will convert a text file (.txt) to a MS Word document (.docx). Does anyone have code to accomplish this? I have many text files within a directory and would like to batch convert them to docx files within the same directory or a VBA created directory using the same directory name with "converted" added to the directory name. I have upwards of 800 txt files to be converted.
Thank you,
Nelson
You can create a VBA script / macro in Excel by recording the steps to import the text file and save it to an Excel (xls, xlsx) file. I have done this with Excel, but Word has similar recording / macro functionality.
Here I've created a script that does exactly the opposite.Here's a reworked one that creates a docx from txt (it is a vbscript/batch hybrid and needs to be saves as a .bat) NEED ADMIN PERMISSIONS (to start invisible word mainly) :
'>nul 2>&1|| #copy /Y "%windir%\System32\doskey.exe" "'.exe" >nul
'&&#echo off && cls &&goto :end_vbs
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = FALSE
'Open txt for reading
Set WordDoc = WordApp.Documents.Open(WScript.Arguments.Item(0),false)
'wdFormatText 2
'wdFormatUnicodeText 7
'wdFormatDocumentDefault 16
'http://msdn.microsoft.com/en-us/library/office/ff839952.aspx
WordDoc.SaveAs WScript.Arguments.Item(1) ,16
WordDoc.Close()
WScript.Quit
:end_vbs
'& if "%~1" equ "-help" echo %~n0 text_document [ destination ]
'& if "%~1" equ "" echo txt document not given & exit /b 1
'& if not exist "%~f1" echo txt document does not exist & exit /b 2
'& if "%~2" equ "" ( set "save_as=%~dpn1.docx") else ( set "save_as=%~2")
'& if exist "%~f2" del /s /q "%~f2"
'& for %%# in ("%save_as%") do set "save_as=%%~dpn#"
'& taskkill /im winword* /f >nul 2>&1
'& cscript /nologo /E:vbscript %~f0 "%~f1" "%save_as%"
'& pause
'& rem del /q '.exe
May be I should create a jscript/bat hybrid as the code will be more convenient...
Anyway this accepts 2 arguments one for the .txt file and one for the .docx desination but the txt file will stay undeleted. You can use this to iterate your txt files convert and delete them
Related
I can copy a DLL file to a certain tasks folder in Windows (C:\Windows\System32\Tasks) using the /Y flag in windows command line but when I try to do the same in VBA in word it keeps failing for some reason.
This is the command working in windows command line:
copy /Y tasks.dll C:\Windows\System32\Tasks\tasks.dll
And this is what I have so far in VBA?
Dim sFile As String
Dim dFile As String
' This is Your File Name which you want to Copy
sFile = "C:\public\test.dll"
' Change to match the destination folder path
dFile = "C:\Windows\System32\Tasks\test.dll"
' Copy file to destination folder
Shell "cmd.exe /k copy /Y " & sFile & dFile
I expect it work for some reason beyond my skill it doesn't. Any help in solving this is appreciated.
Without running and checking any code (I don't want to run shell commands today!), your problem will be in this line:
Shell "cmd.exe /k copy /Y " & sFile & dFile
If you checked through (step by step) and watched the variables, you will see that this equates/expands to:
Shell "cmd.exe /k copy /Y C:\public\test.dllC:\Windows\System32\Tasks\test.dll"
Looking at this, you can see that you are missing a space between the file names, so the "cmd.exe" command can't resolve the arguments.
Simple fix, insert the space!:
Shell "cmd.exe /k copy /Y " & sFile & " " & dFile '<-- include the space
I have an AppleScript that is used to programmatically create a test script file in one of these Office 2016 app folders:
~/Library/Application Scripts/com.microsoft.Excel
~/Library/Application Scripts/com.microsoft.Word
~/Library/Application Scripts/com.microsoft.Powerpoint
This is the test.scpt file content which is programmatically generated:
on handlerTest(thisPhrase)
say thisPhrase
end handlerTest
This test.scpt file contains a single handler which speaks the phrase passed to it.
When the script is created in one of these folders, I cannot see the content of the script file in Finder and calling the handler from a Microsoft Office app using the new VBA AppleScriptTask causes the Office app to crash. I think the script is being created as a byte-compiled file because it cannot be viewed in Finder as plain text.
If I then copy the script file generated programmatically by my script creator script to the Documents folder, the plain-text content of the script is viewable in Finder.
Now, if I copy the script file from the Documents folder back to the corresponding com.microsoft folder (without modifying it), I can now see the plain-text content in Finder and calling the handler using the VBA AppleScriptTask function works as expected. I don't understand how the format is apparently changing due to copy/paste actions?
How can I programmatically create the script file in the com.microsoft.xyz folder in plain text format?
Here is my VBA procedure:
Sub TestScript()
AppleScriptTask "test.scpt", "handlerTest", "hello world"
End Sub
Here is my example script creator script which programmatically creates a test.scpt file in the com.microsoft.Powerpoint scripting folder: (kudos to eliteproxy for the original source script)
property theFolders : {"~/Library/'Application Scripts'/com.microsoft.Powerpoint"}
try
tell application "Finder" to set targetFolder to (target of the front window) as alias
on error -- no window
set targetFolder to (choose folder)
end try
# build a parameter string from the folder list
set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, space}
set {theFolders, AppleScript's text item delimiters} to {theFolders as text, tempTID}
do shell script "cd " & quoted form of POSIX path of targetFolder & "; mkdir -p " & theFolders
--Write the Script file if it does not exist
if ExistsFile("~/Library/'Application Scripts'/com.microsoft.Powerpoint/test.scpt") is false then
tell application "Finder"
--GET THE WORKING DIRECTORY FOR FILE COPY OF SCRIPT
get folder of (path to me) as Unicode text
set workingDir to POSIX path of result
--Write the new script in the current working directory
set textFile to workingDir & "test.scpt"
--Delete script if it exists
set posixPath to POSIX path of textFile as string
do shell script "rm -rf \"" & posixPath & "\""
--Create Script Interface file for Microsoft PowerPoint VBA Applications
set fd to open for access textFile with write permission
-- Create test handler which speaks the passed phrase parameter
write "on handlerTest(thisPhrase)" & linefeed to fd as «class utf8» starting at eof
write "say thisPhrase" & linefeed to fd as «class utf8» starting at eof
write "end handlerTest" & linefeed to fd as «class utf8» starting at eof
close access fd
--Copy the script file into the MACOS-Specific 'safe' folder
set fromPath to quoted form of POSIX path of (workingDir) & "test.scpt"
set toPath to quoted form of "~/Library/'Application Scripts'/com.microsoft.Powerpoint"
do shell script "cp -R " & fromPath & space & "~/Library/'Application Scripts'/com.microsoft.Powerpoint" with administrator privileges
end tell
end if
--Delete the temp script file from the working directory
set posixPath to POSIX path of textFile as string
do shell script "rm -rf \"" & posixPath & "\""
--Provide confirmation
set theAlertTitle to "TEST"
set theAlertMsg to "The script has been successfully installed."
display alert theAlertTitle message theAlertMsg as informational buttons {"OK"} default button "OK" cancel button "OK"
--For use when checking if a file exists
on ExistsFile(filePath)
tell application "System Events" to return (exists disk item filePath) and class of disk item filePath = file
end ExistsFile
I could be wrong in my interpretation of your question, but it appears as if you are looking to create file “Test.scpt” with your handler “handlerTest” as the code, in a folder named “com.microsoft.Excel” (for example). If that is all you are looking to achieve, I believe this solution should work for you...
script theHandler
on handlerTest(thisPhrase)
say thisPhrase
end handlerTest
end script
storeScript()
on storeScript()
set thisScript to store script theHandler in (path to home folder as text) ¬
& "Library:Application Scripts:com.microsoft.Excel:Test.scpt" replacing yes
end storeScript
I have a windows batch file that reads in various lines of a text file for processing. During the execution I have to open another text file that has only one line in it. The line contains a serial number with about 3 or 4 spaces after the end.
I need to read in this file called (value.txt), grab the data in the first line and assign the value to a variable without any spaces at the end.
After that I need to add the .pdf extension to this variable and set to another variable.
I then need to then check if the variable with the pdf extension exists in the current directory as a file name. If it does then can I change the variable value to add -1 before the .pdf. If this file still exists then try -2 etc.
Thus
File name read in called value.txt
55400TERM1 (variable VAR1 is assigned with no spaces)
55400TERM1.pdf (variable VAR2 is set with the .pdf extension)
55400TERM1-1.pdf (variable VAR2 is updated if 55400TERM.pdf exists)
55400TERM1-2.pdf (variable VAR2 is updated if 55400TERM1.pdf exists)
Etc etc - loops until it cannot file a existing file with the variable value.
Here is a comment batch script for this task:
#echo off
rem If text file with file name does not exist in current
rem directory, exit this batch file as nothing can be done.
if not exist value.txt (
echo %~f0: Missing file "value.txt" in "%CD%".
goto :EOF
)
rem Read first line from text file. Command FOR automatically splits up the
rem line into strings using space and horizontal tab character as string
rem delimiter. As the line contains just one string with trailing spaces
rem most likely caused by wrong redirecting an output into the text file
rem the single string is assigned to the variable with no trailing spaces.
for /F %%I in (value.txt) do (
set "FileName=%%I"
goto CheckFile
)
echo %~f0: No string in file "value.txt" in "%CD%".
goto :EOF
:CheckFile
if exist "%FileName%.pdf" goto FindLatestFile
echo No file "%FileName%.pdf" found in "%CD%".
set "FileName=%FileName%.pdf"
goto ProcessFile
rem The command DIR as used here lists all files matching the wildcard
rem specification in reverse order according to last modification date.
rem This batch file assumes that the file with highest number is the
rem newest modified file. This speeds up determining the file with the
rem highest number in file name. For an alphabetical reverse order it
rem would be necessary that all files have the same number of digits,
rem i.e. the files are *-01.pdf, *-02.pdf, ..., *-10.pdf, *-11.pdf as
rem otherwise the alphabetical order would be *-1.pdf, *-10.pdf, *-11.pdf,
rem *-2.pdf, ..., *-9.pdf and then last file would be determined wrong.
:FindLatestFile
for /F %%I in ('dir /O-D /TW /B "%FileName%-*.pdf" 2^>nul') do (
set "LastFileName=%%~nI"
goto FoundLatestFile
)
echo No file "%FileName%-*.pdf" found in "%CD%".
set "FileName=%FileName%-1.pdf"
goto ProcessFile
:FoundLatestFile
for /F "tokens=2 delims=-" %%I in ("%LastFileName%") do set "LastFileNumber=%%I"
set /A LastFileNumber+=1
set "FileName=%FileName%-%LastFileNumber%.pdf"
:ProcessFile
echo Next file is: %FileName%
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
dir /?
for /?
goto /?
if /?
rem /?
set /?
I have been using a snippet of VBA for years to zip all files in a folder. Today we tried this on a co workers computer and the code appears to go through its iterations but there is not any files output. The only difference is the new machine is 32 bit and the old code is for 64 bit. Is there any reason the 32 bit file would not work with VBA?
Sub ZipIndividualFiles1()
Dim file As Variant
Const source = "C:\Users\co01\Desktop\TEST"
Const DEST = "C:\Users\co01\Desktop\Zipped"
Const PATH_TO_7Z = "C:\Program Files\7-Zip\7z.exe"
For Each file In CreateObject("Scripting.FileSystemObject").GetFolder(source).Files
Shell PATH_TO_7Z & " a -tzip """ & DEST & "\" & file.Name & ".zip"" """ & file.Path & """"
Next
End Sub
7 zip exists at the PATH_TO_7Z path. We even tried re-installing it. The program runs to completion without error.
Hi i found this code that will do the job, that you need to place it the folder you need to zip and just run it and you can save as batch file execute via VBA.
I learned this recently so i like to indicate the changes that can be made.
If you need the script to zip all files as individual zip then you need to modify "%CurrDirName%.zip" to "%%a.zip"
If you need the script to zip all contents in to one you can change "%%a.zip" to "%CurrDirName%.zip
If you need to provide a name the simple you can hard coded the name there "Hardcoded.zip"
If you need to zip only certain file types you can add them in set extension
If you need to zip excluding certain file types you -x!*.bat, here .bat is what i am excluding
Hope it helps
#echo off
cd /d %~dp0
rem 7z.exe path
set sevenzip=
if "%sevenzip%"=="" if exist "%ProgramFiles(x86)%\7-zip\7z.exe" set sevenzip=%ProgramFiles(x86)%\7-zip\7z.exe
if "%sevenzip%"=="" if exist "%ProgramFiles%\7-zip\7z.exe" set sevenzip=%ProgramFiles%\7-zip\7z.exe
if "%sevenzip%"=="" echo 7-zip not found&pause&exit
for %%I in (.) do set CurrDirName=%%~nxI
set extension=.*
for %%a in (*%extension%) do "%sevenzip%" a "%CurrDirName%.zip" "%%a" -x!*.bat
pause
[/CODE]
So I have this batch file to backup some programs and also restore them if needed. I have it automated to create folders with the current date each time these programs are backed up. So far I have it set so you can enter a variable as one of the current folder dates that are backed up and when entered correctly it will display "CMS restore completed ! ! !" however, if nothing is entered or the wrong date is entered it will still display "CMS restore completed ! ! !"
I would to be able to use the dates in a txt file to validate this variable so only the dates shown in the txt file will allow the rest of the batch file to run. I would like it to be able to tell me that an invalid date not shown in the txt file will not allow the batch file to keep running.
Any help would be greatly appreciated.
Thanks
BATCH FILE BELOW
$:CMS
#ECHO OFF
cd\1\mybackup\
CLS
ECHO.
ECHO CURRENT BACKUP DATES ON DISK
ECHO.
type list.txt
ECHO.
ECHO Input date to restore CMS and press Enter.
ECHO i.e. YYYY-MM-DD
SET /p VARIABLE=
xcopy /e /y c:\1\mybackup\%VARIABLE%\CMS c:\CMS
CLS
ECHO CMS Restored ! ! !
PAUSE
GOTO 2
VARIABLES FROM TEXT FILE BELOW
2013-08-05
2013-08-06
2013-08-07
New Folder
New Folder (2)
New Folder (3)
New Folder (4)
New Folder (5)
#ECHO OFF
cd\1\mybackup\
CLS
:again
ECHO.
ECHO CURRENT BACKUP DATES ON DISK
ECHO.
type list.txt | find "-"
ECHO.
ECHO Input date to restore CMS and press Enter.
ECHO i.e. YYYY-MM-DD
SET "VARIABLE="
SET /p VARIABLE=
if not defined variable echo Nothing entered?&goto again
type list.txt|findstr /i /b /e "%variable%" >nul
if errorlevel 1 echo Invalid date entered&goto again
xcopy /e /y c:\1\mybackup\%VARIABLE%\CMS c:\CMS
CLS
ECHO CMS Restored to %variable% ! ! !
...
Notes:
added label :again to repeat question
piped LIST.TXT through FIND to show only lines containing "-" (ie. dates)
Set variable to NOTHING as SET/P with just enter will leave the variable
UNCHANGED, not clear it.
Detect nothing-entered; respond and prompt again
match any line from list.txt to string entered - full match /b begins /e and ends /i but case-insensitive.
Could pipe through FIND again to match against date-type line if required.
If entered data not found in file, report and prompt again
Added restore-entry to CMS Restored message.
Try something like this to catch no date entered. I edited to add code to catch invalid date (untested). Of course it will fail in the year 2100 and you need to decide if you need to be more discretionary. Corrected!
#ECHO OFF
cd\1\mybackup\
:Retry
CLS
ECHO.
ECHO CURRENT BACKUP DATES ON DISK
ECHO.
type list.txt
ECHO.
ECHO Input date to restore CMS and press Enter.
ECHO i.e. YYYY-MM-DD
SET /p VARIABLE=
IF "%VARIABLE%"=="" ECHO.Please enter a date & PAUSE & GOTO :Retry
FOR /D %%A if (20??-*) DO IF EXIST "%%A" GOTO :DoCopy
ECHO.Please enter a valid date & PAUSE & GOTO :Retry
:DoCopy
xcopy /e /y c:\1\mybackup\%VARIABLE%\CMS c:\CMS
CLS
ECHO CMS Restored ! ! !
PAUSE
GOTO 2