Please close Excel application - Excel is open - vba

I am not a VB person but I am asked to troubleshoot this issue. We have an Access database that is exporting two Access reports to an Excel workbook. It has been working for years. Recently we are getting an error message that the Excel application is open and must be closed. Both the database and Access template are on a network share drive. From what I can see we are not getting past this point. The server does not show Excel as being opened at the time of the error. I thank you in advance for your assistance.
Here is my code:
Private Sub ExportCounts_Excel()
Dim excelname As String
Dim AppExcel As New Excel.Application
Dim Wkb As Workbook
Dim Wksh As Worksheet
Dim Wksh1 As Worksheet
Dim Wksh2 As Worksheet
Dim obj As AccessObject
Dim dbs As Object
Dim rs As Object
Dim rstable As Object
Dim tempTable As String
Dim data As String
Dim Agent As String
Dim Name As String
Dim newfile As String
Dim tic As String
Dim lastrow As Long
Dim count As Integer
Dim recount As Integer
On Error GoTo Errorcatch
DoCmd.SetWarnings False
'*****************************************************************************
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Call fso.CopyFile("\\cfbf-sql\mbdb\Counts Reports Template.xlsm", "\\cfbf-sql\itdb\IT-Test DBs\counts\Counts Reports.xls")
'see if the excel app is running
Dim MyXL As Object 'Variable to hold reference
Dim ExcelWasNotRunning As Boolean 'Flag for final release
On Error Resume Next
Set MyXL = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
ExcelWasNotRunning = True
End If
'Check if the Excel Application is running
If ExcelWasNotRunning = True Then
'If Excel is running then.............
MsgBox "Please Close your Excel Application" & vbCrLf _
& "and save your files before attempting" & vbCrLf _
& "to run the report", vbInformation, _
"Microsoft Excel is open"
Set MyXL = Nothing
Exit Sub
Else 'Excel is not running
'Optional - to storage the file name entered by user
Dim Message, Title, Default, MyValue
Message = "Enter a name for the file" ' Set prompt.
Title = "Assign File Name" ' Set title.
'Format date to use it as file name and report title
Dim varMonthNum As Variant
Dim varDayNum As Variant
Dim varYear As Variant
Dim varFileDate As Variant
'Get the month, day, and year from LastFriday text box
varMonthNum = Month(LastFriday.Value)
varDayNum = Day(LastFriday.Value)
varYear = Year(LastFriday.Value)
'Format the date to assign it as part of the file name
varFileDate = varMonthNum & "-" & varDayNum & "-" & varYear
'use the following variable to format the file name
Default = Me.CurrentYear.Value & " CFBF Membership Report as of " & varFileDate ' Set default.
' Display message, title, and default value.
MyValue = InputBox(Message, Title, Default)
If StrPtr(MyValue) = 0 Then 'IF the vbCancel Button is selected by the user
'Exit the procedure
Exit Sub
Else 'Create the excel report
'*****************************************************************************
'excelname = "\\member2\MBDB\Counts Reports Template.xls"
excelname = "\\cfbf-sql\MBDB\Counts Reports Template.xls"
'For the new fiscal year 2014
'newfile = "\\web3\FBMNData\WEEKLY COUNTY REPORTS 2011\" & MyValue & ".xls"
'newfile = "\\web3\FBMNData\WEEKLY COUNTY REPORTS 2013\" & MyValue & ".xls"
'newfile = "\\web3\FBMNData\WEEKLY COUNTY REPORTS 2014\" & MyValue & ".xls"
'newfile = "\\web3\FBMNData\WEEKLY COUNTY REPORTS 2015\" & MyValue & ".xls"
'==============================================================================
'**** Comments by: Armando Carrasco - 11/21/2014 ***
'**** MMR - Kate Tscharner - requested to stop posting excel file in ***
'**** the counties FTP site and to place the file in the everyone folder ***
'**** MMR also requested to move all "WEEKLY COUNTY REPORTS YYYY" folders ***
'**** from WEB3 to "\\cfbf-fp\Everyone\MembershipReports\" ***
'newfile = "\\cfbf-fp\Everyone\MembershipReports\WEEKLY COUNTY REPORTS 2015\" & MyValue & ".xls"
'==============================================================================
'**** Comments by: Armando Carrasco - 01/21/2014 ***
'**** MMR - Kate Tscharner - WO 1284 - Comments ***
'**** We have had the request from several county Farm Bureaus to restore ***
'**** Placing the old network directory location in WEB3. ***
newfile = "\\cfbf-reports\FBMNData\WEEKLY COUNTY REPORTS 2017\" & MyValue & ".xls"
'==============================================================================

I'd suggest re-organizing a bit:
Dim MyXL As Object 'Variable to hold reference
Dim ExcelWasRunning As Boolean 'Flag for final release
On Error Resume Next '<< ignore error if Excel not running
Set MyXL = GetObject(, "Excel.Application")
On Error Goto 0 '<< cancel the On Error Resume Next so you
' don't miss later (unexpected) issues
ExcelWasRunning = Not MyXL Is Nothing '<< If Excel was running then MyXL
' is set to the Excel instance
If ExcelWasRunning Then
MsgBox "Please Close your Excel Application" & vbCrLf _
& "and save your files before attempting" & vbCrLf _
& "to run the report", vbInformation, _
"Microsoft Excel is open"
Set MyXL = Nothing
Exit Sub '<< Shouldn't really need this, since the rest of your code
' is in the Else block...
Else
'Excel is not running
'Rest of your code here
End If

Related

VBA to open Excel or/and Word Files

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

vba passing list of variable

I have already created a macro that creates individual files for me. Now having those files I have created another VBA job in outlook that will add the contact information to the e-mail, locate the needed file, and attach it to an e-mail. I need to do this to a list of about 50 different companies that I send these audits to. Currently I need to add a certain parameter to select what company I am using "V003" for example after this job is ran I go to the next one "V004" and so on.
I am looking for a way to provide VBA the list of 50 companies codes into which I have all as folders in a certain directory path. So when i kick off the job it will reference the folder named V003 in the directory path and use that as the VendorID variable I have created then loop back to the beginning and grab the next folder name V004 in the directory path and filter though until it gets to the last one.
Unless someone else has an idea that won't make me kick of the VBA job 50 times and pass in each variable. (Currently that's what I've been doing since I created these jobs and it's still a bit time consuming)
Dim GlobalVarEmail As String
Dim GlobalVarVendorName As String
Dim GlobalVendorId As String
Dim GlobalMonth As String
Dim GlobalYear As String
Dim GlobalAuditDate As String
Sub SendFilesbyEmail()
'the calling method of all sub methods.
GlobalVendorId = InputBox("What Vendor Letter are you trying to send out? (V Code: ex - V012)", "Vendor Code", "Type Here", 7500, 5000)
GlobalMonth = InputBox("What Month are you auditing for?(ex - Jan. Feb. Mar.)", "Month", "Type Here", 7500, 5000)
GlobalYear = InputBox("What year are you auditing for?(ex - 2016)", "Quarter", "Type Here", 7500, 5000)
GlobalAuditDate = InputBox("What is the audit date?(ex - 20160930)", "Quarter", "Type Here", 7500, 5000)
Call openExcel(GlobalVendorId)
Call SendAuditReport
End Sub
Public Function openExcel(UserReponse) As String
'this function is used to retrieve the vendor contact e-mail
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceWS As Worksheet
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = False
.EnableEvents = True
End With
strFile = "G:\403(b)\User Folders\Chris W\SPARK Info\Contacts.xlsx"
Set sourceWB = Workbooks.Open(strFile, , False, , , , , , , True)
Set sourceWH = sourceWB.Worksheets("SPARK")
sourceWB.Activate
Rows("1:1").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$H$100").AutoFilter Field:=1, Criteria1:=UserReponse
Range("F1").Select
GlobalVarEmail = Selection.End(xlDown).Value
Range("B1").Select
GlobalVarVendorName = Selection.End(xlDown).Value
ActiveWorkbook.Close SaveChanges:=False
End Function
Function SendAuditReport()
'this function will create a e-mail, (subjectline & body), attach the needed audit letter, and insert the needed vendor contact e-mail.
Dim Fname As String
Dim sAttName As String
Dim olApp As Outlook.Application
Dim olMsg As Outlook.MailItem
Dim olAtt As Outlook.Attachments
Set olApp = Outlook.Application
Set olMsg = olApp.CreateItem(0) ' email
Set olAtt = olMsg.Attachments
' send message
With olMsg
.Subject = GlobalVarVendorName & " " & GlobalMonth & " " & GlobalYear & " SPARK Audit"
.To = GlobalVarEmail
.CC = "SPARK#AXA.com"
.Attachments.Add "G:\403(b)\User Folders\Chris W\Spark Audit\" & GlobalAuditDate & "\00-Ran Reports\" & GlobalVendorId & "\SPARK Audit Report " & GlobalVarVendorName & ".xlsx"
'you can add attachments here just type .Attachments.Add "folder path"
.HTMLBody = "Hello, <br /><br /> Attached is the file
'.Send
.Display
End With
End Function
You can enumerate folder names as such:
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\pathtoyourparentfolder")
For Each objSubFolder In objFolder.subfolders
MsgBox objSubFolder.Name
Next objSubFolder
objSubFolder.Name will be the name of the folder and you can just pass this to GlobalVendorID.

Reference Excel cell in PowerPoint macro for filename

I can't get SaveAsFixedFormat working from Excel VBA to export a PowerPoint file as PDF. I have resorted to starting a macro in the preset-powerpoint from Excel VBA that exports the presentation as pdf directly from PowerPoint.
Is there any way to reference a cell in the Excel file in this macro that is running in PowerPoint to get the filename?
Sub pppdf()
ActivePresentation.ExportAsFixedFormat "M:\random\test.pdf", 32
End Sub
I can save the PowerPoint file as .pptx from Excel and use varying filenames and paths but now I would like to reference those same paths and filenames in the PowerPoint macro that is exporting to pdf.
In the end I'd like the code to look somewhat like this but this obviously needs some work to function from PowerPoint:
Dim FName As String
Dim FPath As String
FPath = Range("SavingPath").Value
FName = Sheets("randomworksheet").Range("A1").Text
ActivePresentation.ExportAsFixedFormat FPath & FName & " Development" & ".pdf", 32
This PowerPoint macro would be started from Excel and both the PowerPoint file and the Excel Workbook and sheet will be open when this is executed.
Why not open the presentation and save it as a PDF from Excel if the main bulk of the code is in Excel anyway?
Sub SavePPTXasPDF()
Dim PPT As Object
Dim PP As Object
Set PPT = CreatePPT
Set PP = PPT.Presentations.Open("<FullPathToPresentation>")
PP.SaveAs ThisWorkbook.Path & Application.PathSeparator & "ABC", 32 'ppSaveAsPDF
End Sub
Public Function CreatePPT(Optional bVisible As Boolean = True) As Object
Dim oTmpPPT As Object
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Defer error trapping in case Powerpoint is not running. '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next
Set oTmpPPT = GetObject(, "Powerpoint.Application")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'If an error occurs then create an instance of Powerpoint. '
'Reinstate error handling. '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Err.Number <> 0 Then
Err.Clear
On Error GoTo ERROR_HANDLER
Set oTmpPPT = CreateObject("Powerpoint.Application")
End If
oTmpPPT.Visible = bVisible
Set CreatePPT = oTmpPPT
On Error GoTo 0
Exit Function
ERROR_HANDLER:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure CreatePPT."
Err.Clear
End Select
End Function
or if you want to run the code in Powerpoint:
Public Sub Test()
Dim oXL As Object
Dim oWB As Object
Dim FName As String
Dim FPath As String
Set oXL = CreateXL
Set oWB = oXL.workbooks.Open("<Path&FileName>")
'Or if Workbook is already open:
'Set oWB = oXL.workbooks("<FileName>")
FPath = oWB.worksheets("Sheet1").Range("A1")
FName = oWB.worksheets("Sheet1").Range("A3")
ActivePresentation.ExportAsFixedFormat FPath & FName & " Development" & ".pdf", 32
End Sub
Public Function CreateXL(Optional bVisible As Boolean = True) As Object
Dim oTmpXL As Object
'''''''''''''''''''''''''''''''''''''''''''''''''''''
'Defer error trapping in case Excel is not running. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next
Set oTmpXL = GetObject(, "Excel.Application")
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
'If an error occurs then create an instance of Excel. '
'Reinstate error handling. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Err.Number <> 0 Then
Err.Clear
On Error GoTo ERROR_HANDLER
Set oTmpXL = CreateObject("Excel.Application")
End If
oTmpXL.Visible = bVisible
Set CreateXL = oTmpXL
On Error GoTo 0
Exit Function
ERROR_HANDLER:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure CreateXL."
Err.Clear
End Select
End Function
Or you could, as you requested, open the presentation from within Excel and execute code stored in the presentation:
Sub SavePPTXasPDF()
Dim PPT As Object
Dim PP As Object
Set PPT = CreatePPT
Set PP = PPT.Presentations.Open("<FullPath>")
PPT.Run PP.Name & "!Test"
End Sub
This would use the Test macro and use the Set oWB = oXL.workbooks("<FileName>") line of code which is currently commented out in my example above.
What problem are you facing using ExportAsFixedFormat directly from the Excel VBE? According to the documentation (which seems to be incorrect) and the PowerPoint VBE IntelliSense, the second argument, FixedFormatType can only be one of two values:
ExportAsFixedFormat(Path, FixedFormatType, Intent, FrameSlides, _
HandoutOrder, OutputType, PrintHiddenSlides, PrintRange, _
RangeType, SlideShowName, IncludeDocProperties, KeepIRMSettings)
FixedFormatType:
ppFixedFormatTypePDF = 2
ppFixedFormatTypeXPS = 1

Embedding Several Images into an Email using VBA from Excel to Outlook and using CID

I'm trying to embed several graphs (as PNGs) from a Excel VBA Macro to Outlook.
The images embed however, it's not all 8 images but the first one repeated 8 times.
Sub Test()
Dim sheetNumber, size, i As Integer
Dim chartNames(), FNames() As String
Dim objChrt As ChartObject
Dim myChart As Chart
'Activate Charts Sheet
Sheets("GRAFICAS").Activate
'Calculate Number of Charts in Sheet
chartNumber = ActiveSheet.ChartObjects.Count
'Redimension Arrays to fit all Chart Export Names
ReDim chartNames(chartNumber)
ReDim FNames(chartNumber)
'Loops through all the charts in the GRAFICAS sheet
For i = 1 To chartNumber
'Select chart with index i
Set objChrt = ActiveSheet.ChartObjects(i)
Set myChart = objChrt.Chart
'Generate a name for the chart
chartNames(i) = "myChart" & i & ".png"
On Error Resume Next
Kill ThisWorkbook.Path & "\" & chartNames(i)
On Error GoTo 0
'Export Chart
myChart.Export Filename:=Environ$("TEMP") & "\" & chartNames(i), Filtername:="PNG"
'Save path to exported chart
FNames(i) = Environ$("TEMP") & "\" & chartNames(i)
Next i
'Declare the Object variables for Outlook.
Dim objOutlook As Object
'Verify Outlook is open.
On Error Resume Next
Set objOutlook = GetObject(, "Outlook.Application")
'If Outlook is not open, end the Sub.
If objOutlook Is Nothing Then
Err.Clear
MsgBox _
"Cannot continue, Outlook is not open.", , _
"Please open Outlook and try again."
Exit Sub
'Outlook is determined to be open, so OK to proceed.
Else
'Establish an Object variable for a mailitem.
Dim objMailItem As Object
Set objMailItem = objOutlook.CreateItem(0)
'Build the mailitem.
Dim NewBody As String
On Error Resume Next
With objMailItem
.To = "dummy#test.com"
.Subject = "Testing Lesson 31 email code"
.Importance = 1 'Sets it as Normal importance (Low = 0 and High = 2)
'Change the Display command to Send without reviewing the email.
' .Display
End With
For i = 1 To chartNumber
objMailItem.Attachments.Add FNames(i)
'Put together the HTML to embed
NewBody = NewBody + HTMLcode & "<div align=center>" & "<IMG src=cid: myChart" & i & ".png></img>" & "</div>"
Next
MsgBox NewBody
'Set the HTML body
objMailItem.HTMLBody = NewBody
'Display email before sending
objMailItem.Display
'Close the If block.
End If
Kill Fname
End Sub
MsgBox NewBody outputs:
and the final email looks like:
It should show all charts one below the other one, however it only takes myChart1.png and repeats it 8 times, despite the output of NewBody.
What am I doing wrong? I'm using Outlook 2013 and Excel 2013
UPDATE: I added another image and it seems to, in this case, repeat the last image I added 9 times (same as number of attached images). I'm guessing it's a problem with the cid, maybe ids aren't unique?
You must set the PR_ATTACH_CONTENT_ID property on the attachment appropriately to match the value of the cid attribute:
Set attach = objMailItem.Attachments.Add(FNames(i))
'Put together the HTML to embed
Dim cid
cid = "myChart" & i & ".png"
NewBody = NewBody + HTMLcode & "<div align=center>" & "<IMG src=cid:" & cid & "</img>" & "</div><br><br>"
Call attach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", cid)

How do I merge multiple selected excel files in VBA?

I'm new with VBA and I'm wondering on how to merge multiple selected excel files using VBA. I tried coding the part of selecting files. I've researched and tried copying the codes on the internet and did some editing. I learned that you can add filters so I did that. But sometimes, the excel files won't show even if I added the correct filter (based on what I've researched). I really need to merge multiple selected excel files. I hope you can help me.
I'm using a userform, btw. One button that would allow to select and merge the selected files. And if possible, I want the user to see the path of the selected files. I don't know yet on how to do that, or what tool should I use, like listbox or what. Thanks in advance!
Update!
I have a code for selecting multiple excel files. What I need now is how to merge the files that I selected.
Dim FileNames As Variant
Dim Msg As String
Dim I As Integer
FileNames = Application.GetOpenFilename(MultiSelect:=True)
If IsArray(FileNames) Then
Msg = "You selected:" & vbNewLine
For I = LBound(FileNames) To UBound(FileNames)
Msg = Msg & FileNames(I) & vbNewLine
Next I
MsgBox Msg
tbPath.Value = Msg
Else
MsgBox "No files were selected."
End If
Well here is my code... hope this help you.
Sub mergeAllFiles()
Dim This As Workbook 'Store the book with the macro
Dim TmpB As Workbook 'store the book that has the sheets (one per book)
Dim AllB As Workbook 'book to send all the books
Dim sht As Worksheet 'the only sheet every book
Dim FileNames As Variant
Dim Msg As String
Dim I As Integer
Set This = ThisWorkbook
FileNames = Application.GetOpenFilename(MultiSelect:=True)
If IsArray(FileNames) Then
Workbooks.Add 'add a new book to store all the sheets
Set AllB = ActiveWorkbook
AllB.SaveAs This.Path & "\allSheetsInOne" & SetTimeName & ".xlsx", 51
'The function is to store a different name every time and avoid error
Msg = "You selected:" & vbNewLine
For I = LBound(FileNames) To UBound(FileNames)
Workbooks.Open Filename:=FileNames(I)
Set TmpB = ActiveWorkbook
TmpB.Activate
Set sht = ActiveSheet 'because you say that the book has only one sheet
sht.Copy Before:=AllB.Sheets(Sheets.Count) 'send it to the end of the sheets
TmpB.Close 'we don't need the book anymore
Set TmpB = Nothing 'empty the var to use it again
Set sht = Nothing
Msg = Msg & FileNames(I) & vbNewLine
Next I
MsgBox Msg
tbPath.Value = Msg
Else
MsgBox "No files were selected."
End If
End Sub
Function SetTimeName()
Dim YY
Dim MM
Dim DD
Dim HH
Dim MI
Dim SS
Dim TT
YY = Year(Date)
MM = Month(Date)
DD = Day(Date)
HH = Hour(Now)
MI = Minute(Now)
SS = Second(Now)
TT = Format(YY, "0000") & Format(MM, "00") & Format(DD, "00") & Format(HH, "00") & Format(MI, "00") & Format(SS, "00")
SetTimeName = TT
End Function
Tell me if is need it any improvement.
Use my code from here:
Multi-Select Files and open
Edit the code to suite your requirements.
Sub OPenMultipleWorkbooks()
'Open Multiple .xlsx files
Application.DisplayAlerts = False
Dim wb As Workbook, bk As Workbook
Dim sh As Worksheet
Dim GetFile As Variant, Ws As Worksheet
Set wb = ThisWorkbook
Set sh = wb.ActiveSheet
For Each Sheet In Sheets
If Sheet.Name <> sh.Name Then Sheet.Delete
Next Sheet
ChDrive "C:"
Application.ScreenUpdating = False
GetFile = Application.GetOpenFilename(FileFilter:="XLSX(*.xlsx), *.xlsx", Title:="Open XLSX- File", MultiSelect:=True)
On Error Resume Next
If GetFile <> False Then
On Error GoTo 0
For i = 1 To UBound(GetFile)
Set bk = Workbooks.Open(GetFile(i))
Sheets(1).Move Before:=wb.Sheets(1)
bk.Close True
Next i
End If
End Sub