VBA to open Excel or/and Word Files - vba

I'm trying to setup a command button in a user form to allow the user to open either an Excel and/or a Word Document one at a time or both at the same time. But so far I'm able only to select and open Excel but not Word files with the following code:
Sub OpeningExcelFile()
Dim Finfo As String
Dim FilterIndex As Integer
Dim Title As String
Dim Filename As Variant
Dim wb As Workbook
'Setup the list of file filters
Finfo = "Excel Files (*.xlsx),*xlsx," & _
"Macro-Enable Worksheet (*.xlsm),*xlsm," & _
"Word Files (*.docx),*.docx," & _
"All Files (*.*),*.*"
MultiSelect = True
'Display *.* by default
FilterIndex = 4
'Set the dialog box caption
Title = "Select a File to Open"
'Get the Filename
Filename = Application.GetOpenFilename(Finfo, _
FilterIndex, Title)
'Handle return info from dialog box
If Filename = False Then
MsgBox "No file was selected."
Else
MsgBox "You selected " & Filename
End If
On Error Resume Next
Set wb = Workbooks.Open(Filename)
Do you know what it is missing?

You cannot open word files with Excel Application.
You need to have check like below to handle this.
Dim objWdApp As Object
Dim objWdDoc As Object
If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
Set objWdApp = CreateObject("Word.Application")
objWdApp.Visible = True
Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document
Else
Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet
End If

Related

Excel File not Visible but Word file is

Form Workbook1 I'm launching the Opening_File Userform using the following code to keep the application hide and the form visible:
Sub ShowingForm()
Opening_File.Show (vbModeless)
Application.Visible = False
ThisWorkbook.Windows(1).Visible = False
End Sub
and I use the following code to open Excel and Word Files from the form:
Sub OpeningExcelFile()
Dim Finfo As String
Dim FilterIndex As Integer
Dim Title As String
Dim Filename As Variant
Dim wb As Workbook
Dim objWdApp As Object
Dim objWdDoc As Object
'Setup the list of file filters
Finfo = "Excel Files (*.xlsx),*xlsx," & _
"Macro-Enable Worksheet (*.xlsm),*xlsm," & _
"Word Files (*.docx),*.docx," & _
"All Files (*.*),*.*"
MultiSelect = True
'Display *.* by default
FilterIndex = 4
'Set the dialog box caption
Title = "Select a File to Open"
'Get the Filename
Filename = Application.GetOpenFilename(Finfo, _
FilterIndex, Title)
'Handle return info from dialog box
If Filename = False Then
MsgBox "No file was selected."
Exit Sub
Else
MsgBox "You selected " & Filename
End If
If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
Set objWdApp = CreateObject("Word.Application")
objWdApp.Visible = True
Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document
Else
Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet
End If
End Sub
Opening Word files is not a problem but whenever I open Excel Files since Application.Visible = False, I have to Hide the form with :
Private Sub CommandButton2_Click()
Opening_File.Hide
Application.Visible = True
ThisWorkbook.Windows(1).Visible = True
End Sub
So I'm able to see the excel file opened. Is there anyway to keep the form visible with the workbook where I'm launching the form not visible but every workbook I open from the form visible? Thank you
I realize the best way to go in this kind of situations is to leave the ThisWorkbook.Windows(1).Visible = False witch would leave the application visible and also will allow me to see each workbook file opened from the form.
Sub ShowingForm()
Opening_File.Show (vbModeless)
Application.Visible = True
ThisWorkbook.Windows(1).Visible = False
End Sub

HOW To manipulate an ALREADY open word document from excel vba

I am new to VBA and obviously I am missing something. My code works for opening a word doc and sending data to it BUT does NOT for an ALREADY OPEN word doc. I keep searching for an answer on how to send info from Excel to an OPEN Word doc/Bookmark and nothing works.
I hope it is okay that I added all the code and the functions called. I really appreciate your help!
What I have so far
Sub ExcelNamesToWordBookmarks()
On Error GoTo ErrorHandler
Dim wrdApp As Object 'Word.Application
Dim wrdDoc As Object 'Word.Document
Dim xlName As Excel.Name
Dim ws As Worksheet
Dim str As String 'cell/name value
Dim cell As Range
Dim celldata As Variant 'added to use in the test
Dim theformat As Variant 'added
Dim BMRange As Object
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Set wb = ActiveWorkbook
strPath = wb.Path
If strPath = "" Then
MsgBox "Please save your Excel Spreadsheet & try again."
GoTo ErrorExit
End If
'GET FILE & path of Word Doc/Dot
strPathFile = strOpenFilePath 'call a function in MOD1
If strPathFile = "" Then
MsgBox "Please choose a Word Document (DOC*) or Template (DOT*) & try again." 'strPath = Application.TemplatesPath
GoTo ErrorExit
End If
If FileLocked(strPathFile) Then 'Err.Number = 70 if open
'read / write file in use 'do something
'NONE OF THESE WORK
Set wrdApp = GetObject(strPathFile, "Word.Application")
'Set wrdApp = Word.Documents("This is a test doc 2.docx")
'Set wrdApp = GetObject(strPathFile).Application
Else
'all ok 'Create a new Word Session
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
wrdApp.Activate 'bring word visiable so erros do not get hidden.
'Open document in word
Set wrdDoc = wrdApp.Documents.Open(Filename:=strPathFile) 'Open vs wrdApp.Documents.Add(strPathFile)<=>create new Document1 doc
End If
'Loop through names in the activeworkbook
For Each xlName In wb.Names
If Range(xlName).Cells.Count = 1 Then
celldata = Range(xlName.Value)
'do nothing
Else
For Each cell In Range(xlName)
If str = "" Then
str = cell.Value
Else
str = str & vbCrLf & cell.Value
End If
Next cell
'MsgBox str
celldata = str
End If
'Get format and strip away the spacing, negative color etc etc
'I know this is not right... it works but not best
theformat = Application.Range(xlName).DisplayFormat.NumberFormat
If Len(theformat) > 8 Then
theformat = Left(theformat, 5) 'was 8 but dont need cents
Else
'do nothing for now
End If
If wrdDoc.Bookmarks.Exists(xlName.Name) Then
'Copy the Bookmark's Range.
Set BMRange = wrdDoc.Bookmarks(xlName.Name).Range.Duplicate
BMRange.Text = Format(celldata, theformat)
'Re-insert the bookmark
wrdDoc.Bookmarks.Add xlName.Name, BMRange
End If
Next xlName
'Activate word and display document
With wrdApp
.Selection.Goto What:=1, Which:=2, Name:=1 'PageNumber
.Visible = True
.ActiveWindow.WindowState = wdWindowStateMaximize 'WAS 0 is this needed???
.Activate
End With
GoTo WeAreDone
'Release the Word object to save memory and exit macro
ErrorExit:
MsgBox "Thank you! Bye."
Set wrdDoc = Nothing
Set wrdApp = Nothing
Exit Sub
'Error Handling routine
ErrorHandler:
If Err Then
MsgBox "Error No: " & Err.Number & "; There is a problem"
If Not wrdApp Is Nothing Then
wrdApp.Quit False
End If
Resume ErrorExit
End If
WeAreDone:
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
file picking:
Function strOpenFilePath() As String
Dim intChoice As Integer
Dim iFileSelect As FileDialog 'B
Set iFileSelect = Application.FileDialog(msoFileDialogOpen)
With iFileSelect
.AllowMultiSelect = False 'only allow the user to select one file
.Title = "Please... Select MS-WORD Doc*/Dot* Files"
.Filters.Clear
.Filters.Add "MS-WORD Doc*/Dot* Files", "*.do*"
.InitialView = msoFileDialogViewDetails
End With
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strOpenFilePath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
Else
'nothing yet
End If
End Function
checking if file is open...
Function FileLocked(strFileName As String) As Boolean
On Error Resume Next
' If the file is already opened by another process,
' and the specified type of access is not allowed,
' the Open operation fails and an error occurs.
Open strFileName For Binary Access Read Write Lock Read Write As #1
Close #1
' If an error occurs, the document is currently open.
If Err.Number <> 0 Then
' Display the error number and description.
MsgBox "Function FileLocked Error #" & str(Err.Number) & " - " & Err.Description
FileLocked = True
Err.Clear
End If
End Function
ANSWER BELOW. Backstory... So, after input from you guys and more research I discovered that I needed to set the active word document by using the file selection the user picked and that is then passed via late binding to the sub as an object to process. NOW it works if the word file is not in word OR if it is currently loaded into word AND not even the active document. The below code replaces the code in my original question.
Set Object app as word.
grab the file name.
Make the word doc selected active to manipulate.
Set the word object to the active doc.
THANK YOU EVERYONE!
If FileLocked(strPathFile) Then 'Err.Number = 70 if open
'read / write file in use 'do something
Set wrdApp = GetObject(, "Word.Application")
strPathFile = Right(strPathFile, Len(strPathFile) - InStrRev(strPathFile, "\"))
wrdApp.Documents(strPathFile).Activate ' need to set picked doc as active
Set wrdDoc = wrdApp.ActiveDocument ' works!
This should get you the object you need.
Dim WRDFile As Word.Application
Set WRDFile = GetObject(strPathFile)
'Have Microsoft Word 16.0 Object Library selected in your references
Dim wordapp As Object
Set wordapp = GetObject(, "Word.Application")
wordapp.Documents("documentname").Select
'works if you only have one open word document. In my case, I'm trying to push updates to word links from excel.

Trying to save word file, from excel vba, without over-writing any existing files

Trying to save word file, from excel vba, without over-writing any existing files. The possibility exists that the filename chosen (taken from the spreadsheet) may be a duplicate, in which case I would like to pause or stop the code, but instead it over-writes automatically) As below, though my two prong attempt to error catch fails, and the word document is over written:
Sub automateword()
Dim fileToOpen As String
Dim intChoice As Integer
Dim myFile As Object
mysheet = ActiveWorkbook.Name
Set Wst = Workbooks(mysheet).ActiveSheet
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
'get the file path selected by the user
fileToOpen = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
End If
Set wordapp = CreateObject("word.Application")
Set myFile = wordapp.documents.Add(fileToOpen)
i = 1
Do Until IsEmpty(Wst.Cells(i, 2))
i = i + 1
Loop
i = i - 1
wordapp.Visible = True
Filename = Wst.Cells(i, 2) + " " + Wst.Cells(i, 3) + Str(Wst.Cells(i, 10))
On Error GoTo errorline
wordapp.DisplayAlerts = True
FullPath = "\\networkpath\" & Filename & ".doc"
myFile.SaveAs (FullPath)
Exit Sub
errorline:
MsgBox ("filename error")
End Sub
You can add this if-statement before adding a word document.
If Dir(fileToOpen) <> "" Then Exit Sub

Excel VBA, using FileDialog to open multiple workbooks and reference them

I am currently using to following code to prompt the user for a workbook, open it, get some information from it and then close it. at the moment, I address the opened workbook by using the workbooks collection with and index ("woorkbooks(2)"). Now I need to open two workbooks, and my problem is that I wouldn't know which of the workbooks will be indexed as 2 and which will be indexed as 3. So, I figured there must be a way to get a reference to each workbook.
Function openfile() As Boolean
Dim fd As FileDialog
Dim file_was_chosen As Boolean
Set fd = Application.FileDialog(msoFileDialogOpen)
With fd
.Filters.Clear
.Filters.Add "Excel File", "*.xl*"
End With
file_was_chosen = fd.Show
If Not file_was_chosen Then
MsgBox "You didn't select a file"
openfile = False
Exit Function
End If
fd.Execute
openfile = True
End Function
Now I've seen some solutions to this problem involving getting the full path of each workbook, but I'd prefer avoid using the full path since it contains words in different language (and the name of the workbook appears with question marks). Moreover, I'd prefer a solution in which the user is promped only once for 2 files and not twice.
This version gives the user a single dialog. Enjoy. And whoever downvoted my other answer, please add a comment to that explaining what you so disliked about it that it required a downvote.
Function openfile() As Variant
Dim aOpen(2) As String, itm As Variant, cnt As Long, lAsk As Long
Dim fd As FileDialog
Dim file_was_chosen As Boolean
Set fd = Application.FileDialog(msoFileDialogOpen)
With fd
.Filters.Clear
.Filters.Add "Excel File", "*.xl*"
End With
Do
file_was_chosen = fd.Show
If Not file_was_chosen Or fd.SelectedItems.Count > 2 Then
lAsk = MsgBox("You didn't select one or two files, try again?", vbQuestion + vbYesNo, "File count mismatch")
If lAsk = vbNo Then
openfile = aOpen
Exit Function
End If
End If
Loop While fd.SelectedItems.Count < 1 Or fd.SelectedItems.Count > 2
cnt = 0
For Each itm In fd.SelectedItems
aOpen(cnt) = itm
cnt = cnt + 1
Next
openfile = aOpen
fd.Execute
End Function
Sub test()
Dim vRslt As Variant
Dim wkb As Excel.Workbook, wkb1 As Excel.Workbook, wkb2 As Excel.Workbook
vRslt = openfile
For Each wkb In Application.Workbooks
If wkb.Path & "\" & wkb.Name = vRslt(0) Then Set wkb1 = wkb
If wkb.Path & "\" & wkb.Name = vRslt(1) Then Set wkb2 = wkb
Next
If vRslt(0) = "" Then ' no files
MsgBox "No files opened so nothing happens..."
ElseIf vRslt(1) = "" Then ' one file was opened
MsgBox "One file so do whatever you want for one file"
Else ' two files were opened
MsgBox "Two files so do whatever you want for two files"
End If
End Sub
Working with your existing openfile function, change the return from Boolean to Excel.Workbook. If they don't open a workbook you set it to Nothing instead of false, otherwise you set it to the workbook reference of the file you just opened (You'll need to modify openfile to get that reference). You then just call it twice and set a workbook reference for each call that is not Nothing.
Example code below is written freeform and is untested - it's really just glorified pseudocode - but should point you the right general direction.
sub test
dim lAsk as long
dim wkb1 as excel.workbook
dim wkb2 as excel.workbook
do
if wkb1 is Nothing then
set wkb1 = openfile
if wkb1 is Nothing then
lAsk = msgbox("you didn't select a first file, try again?",vbyesno,"No file selected")
if lAsk = vbNo then exit do
end if
elseif wkb2 is Nothing then
set wkb2 = openfile
if wkb2 is Nothing then
lAsk = msgbox("you didn't select a second file, try again?",vbyesno,"No file selected")
if lAsk = vbNo then exit do
end if
end if
loop while wkb1 is Nothing or wkb2 is Nothing
' do whatever with wkb1 and wkb2 here
end sub
Edited to add:
Here's a very basic shape for your revised openfile function. Again, untested but I've modified it from one of my own procs so it should work
Function openfile() As Excel.Workbook
Dim sFilter As String
Dim sTitle As String
Dim vFileName As Variant
sFilter = "Excel Files (*.xl*), *.xl*, CSV Files (*.csv), *.csv, All Files (*.*), *.*"
sTitle = "Select file to process"
vFileName = Application.GetOpenFilename(filefilter:=sFilter, Title:=sTitle)
If vFileName = False Then
Set openfile = Nothing
Else
Set openfile = Workbooks.Open(Filename:=vFileName)
End If
End Function

Calculate sum of the cells in excel using lotusscript

I have a form, within the form I have an object (worksheet) that has excel file in it.
Then I have a button that would calculate the sum of the field in the worksheet, and displays it's sum in the field of the form. How do I code that? The idea is like this
totalr = SUM (A2:A51)
doc.total = totalr
If you're doing this on a form that will be used from a Notes client and the machine running the Notes client has Excel then you can use VBA. Just extract the file to the user's hard drive, open it with Excel, add a cell at the bottom of the column and put a SUM() function there, get that new cell's value, update the field in the UIDOC and then erase the temp file.
The code below presumes you have a form with a RichText field (containing the Excel file) called "excelfile", a field called "Sum" that will contain the sum value from the Excel file, and a button that contains the code. Additionally the document will have to be saved with the attachment for the code to work.
Hope it helps.
Sub Click(Source As Button)
On Error Goto errorhandler
Dim s As New NotesSession
Dim ws As New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set uidoc = ws.CurrentDocument
Dim doc As NotesDocument
Set doc = uidoc.Document
Dim rtitem As NotesRichTextItem
Dim isfileopen As Boolean
Dim filename As String, rows As Double, cols As Double, colToSum As String, c As Integer
Dim xlApp As Variant, xlWorkbook As Variant, xlSheet As Variant, pathname As String
isfileopen = False
'convert column letter to number
colToSum = "A"
c = Asc(colToSum) - 64
'extract file
pathname = s.GetEnvironmentString( "Directory", True ) & "\"
Set rtitem = doc.GetFirstItem("excelfile")
If Not (doc.HasEmbedded) Then
Msgbox "There are no file attachments on this document"
Goto ExitGracefully
End If
Forall o In rtitem.EmbeddedObjects
If ( o.Type = EMBED_ATTACHMENT ) Then
filename = pathname & o.Name
Call o.ExtractFile( filename )
End If
End Forall
'open file
Print "Opening file " & filename & "..."
Set xlApp = CreateObject("Excel.Application")
xlApp.Workbooks.Open filename
isfileopen = True
'get sheet
Print "Gathering data ..."
Set xlWorkBook = xlApp.ActiveWorkbook
Set xlSheet = xlWorkBook.ActiveSheet
xlSheet.Cells.SpecialCells(11).Activate
rows = xlApp.ActiveWindow.ActiveCell.Row
cols = xlApp.ActiveWindow.ActiveCell.Column
'add a row and put the sum() formula there
Print "Computing sum with Excel..."
xlSheet.Cells( rows+1, c ).value = "=SUM(" & colToSum & "1:" & colToSum & Cstr(rows) & ")"
'update UI doc
Call uidoc.FieldSetText( "Sum", Cstr(xlSheet.Cells( rows+1, c ).value) )
exitgracefully:
'close excel
Print "Closing Excel..."
If Not xlWorkbook Is Nothing Then
xlWorkbook.Close False
End If
If Not xlApp Is Nothing Then
xlApp.DisplayAlerts = False
xlApp.Quit
Set xlApp = Nothing
End If
If isfileopen Then
'remove temp file
Print "Removing " & filename
Kill filename
End If
'done
Print "Done"
Exit Sub
errorhandler:
Msgbox Error & " line " & Erl
Exit Sub
End Sub