I've written some Word VBA which takes an Excel file and updates Labels (ActiveX Control) in the Word file. The only thing is this Excel file will change path and filename each month. Instead of editing 2 variables each month, how do I add an Open File dialog box so the user selects the Excel file to be used?
Here is what I have now:
Sub Update()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
PathWork = "C:\My Documents\2015-05 Report\"
CalcFile = "May2015-data.xlsx"
Set exWb=objExcel.Workbooks.Open(FileName:=PathWork & CalcFile)
ThisDocument.date.Caption=exWb.Sheets("Data").Cells(1,1)
End Sub
Here is a simplified macro which will allow the user to select only Macro-Enabled Excels. I couldn't comment on the previous answer as I have not earned enough reputation to comment on an answer. Please mind it.
Public Sub GetCaptionFromExcel()
Dim objExcel As New Excel.Application, exWb As Workbook
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select Macro-Enabled Excel Files"
.Filters.Add "Macro-Enabled Excel Files", "*.xlsm", 1
If .Show <> -1 Then Exit Sub
Set exWb = objExcel.Workbooks.Open(.SelectedItems(1))
'*** Use the values from excel here***
MsgBox exWb.Sheets("Data").Cells(1, 1)
'*** Close the opened Excel file
exWb.Close
End With
End Sub
You could try something like this
Replace PathWork and CalcFile with Dialogbox
With Dialogs(wdDialogFileOpen)
If .Display Then
If .Name <> "" Then
Set exWb = Workbooks.Open(.Name)
sPath = exWb.Path
End If
Else
MsgBox "No file selected"
End If
End With
Complete CODE should look like this
Option Explicit
Sub Update()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim sPath As String
'// Dialog box here to select excel file
With Dialogs(wdDialogFileOpen)
If .Display Then
If .Name <> "" Then
Set exWb = Workbooks.Open(.Name)
sPath = exWb.Path
End If
Set exWb = objExcel.Workbooks.Open(FileName:=sPath)
ActiveDocument.Date.Caption = exWb.Sheets("Data").Cells(1, 1)
Else
MsgBox "No file selected"
End If
End With
Set objExcel = Nothing
Set exWb = Nothing
End Sub
Related
I'm trying to set the default directory for the VBA function GetOpenfilename. I managed to get it working before but lost the code before saving it.
Sub Sample2()
Dim myFile As Variant
Dim i As Integer
Dim myApp As Excel.Application
Dim strCurDir As String
Set myApp = New Excel.Application
ChDrive ("H:\")
ChDir ("H:\99 - Temp")
'Open File to search
myFile = myApp.GetOpenFileName(MultiSelect:=True)
If myFile <> False Then
If IsArray(myFile) Then '<~~ If user selects multiple file
For i = LBound(myFile) To UBound(myFile)
Debug.Print myFile(i)
Next i
Else '<~~ If user selects single file
Debug.Print myFile
End If
Else
Exit Sub
End If
End Sub
I tried several variations of this code and the posts I found are very old. It is going to be part of a bigger code in Outlook 2016.
Try the FileDialog property of the Excel object instead...
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
Dim myFile As Variant
With xlApp.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
.ButtonName = "Select"
.Title = "Select File"
.InitialFileName = "H:\99 - Temp\"
If .Show = 0 Then Exit Sub 'user cancelled
For Each myFile In .SelectedItems
Debug.Print myFile
Next myFile
End With
Set xlApp = Nothing
I need some help with some bizzare VBA code behavior in Powerpoint. Purpose is simple - update Excel links on a Powerpoint presentation. I have a presentation with objects linked to an Excel file. On running the code from Powerpoint, a user is prompted to select the source Excel file on the harddrive, and the location of this Excel file is used to replace the previous location of the Excel file, already saved in the PowerPoint presentation.
You run the macro, check the links, their path is updated. You click save, close the presentation. You open the presentation and all is good.
Now let’s say you change the name of the Excel file. You run the macro, check the links, their path is updated. You click save, close the presentation. You open the presentation and ONLY HALF THE LINKS ARE UPDATED. Could somebody take a look? Thanks!
Private Sub CommandButton1_Click()
Dim xlApp As Object
Dim xlWorkBook As Object
Dim pptSlide As Slide
Dim pptShape As Shape
Dim oldString, tempString, newString As String
Dim intLength As Integer
Dim sPath As String
Dim ExcelFileName As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file to update links in the presentation"
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel Workbook", "*.xlsx"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
newString = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
'show "macro running" screen
UserForm1.Show False
'open excel file with links
Set xlApp = CreateObject("Excel.Application")
Set xlWorkBook = xlApp.Workbooks.Open(newString, True, False)
'grab old full path to replace link in objects
For Each pptSlide In ActivePresentation.Slides
For Each pptShape In pptSlide.Shapes
If pptShape.Type = msoLinkedOLEObject Then
tempString = pptShape.LinkFormat.SourceFullName
intLength = InStr(tempString, "!")
oldString = Mid(tempString, 1, intLength - 1)
GoTo 1
End If
If pptShape.Type = msoChart Then
oldString = pptShape.LinkFormat.SourceFullName
GoTo 1
End If
Next pptShape
Next pptSlide
1
'replace old full path to new full path
For Each pptSlide In ActivePresentation.Slides
For Each pptShape In pptSlide.Shapes
If pptShape.Type = msoLinkedOLEObject Or pptShape.Type = msoChart Then
With pptShape.LinkFormat
If InStr(1, UCase(.SourceFullName), UCase(oldString)) Then
.SourceFullName = Replace(.SourceFullName, oldString, newString)
End If
End With
pptShape.LinkFormat.Update
End If
'DoEvents
Next pptShape
'DoEvents
Next pptSlide
'close excel file with links
xlWorkBook.Close (False)
xlApp.Quit
Set xlApp = Nothing
Set xlWorkBook = Nothing
'hide "macro running" screen
UserForm1.Hide
End Sub
I am using MSO Access 2013, and writing some code to open the file dialog for the user to select an Excel file to import information in to a table in the database. I get the Runtime error, and not exactly sure why. Would anyone kindly help with this situation? The code is as follows
Dim xlApp As Excel.Application
Dim xlWrksht As Excel.Worksheet
Dim xl As Excel.Application
Dim xlsht As Excel.Worksheet
Dim xlWrkBk As Excel.Workbook
If MsgBox("This will create a new job by importing a Start Up worksheet.
Do you want to continue?", vbYesNo + vbQuestion, "Well Startup - Import
File") = vbYes Then
'prompt user for file
Const msoFileDialogFilePicker As Long = 3
Dim objDialog As Object
Dim fPath As String
Set objDialog = Application.FileDialog(msoFileDialogFilePicker)
With objDialog
.AllowMultiSelect = False
.Show
If .SelectedItems.Count = 0 Then
MsgBox "No file selected."
Exit Sub
Else
fPath = .InitialFileName
End If
End With
'open db and store data in tables
Set myRec = CurrentDb.openrecordset("WellProject")
Set xlApp = CreateObject("Excel.Application")
Set xlWrksht = xlApp.Open(fPath).Worksheets("1") '<----where I get the error
Set xl = CreateObject("Excel.Application")
Set xlWrkBk = GetObject(fPath)
Set xlsht = xlWrkBk.Worksheets(1)
'1st table
myRec.AddNew
myRec.Fields("Job") = xlWrksht.Cells(2, "F")
myRec.Fields("spud_date") = xlWrksht.Cells(10, "B")
myRec.Update
Else: Exit Sub
End If
The directory path is stored in the variable fPath. This works fine. I believe the issue would be somewhere with the Excel file, but not sure. Any ideas? Thanks everyone!
I'm using VBA in powerPoint to update links to Excel Objects in my PowerPoint and everything is working well. The only Issue I have is that sometimes the Select File dialogue box opens behind the active Powerpoint and the only way to select it is to CTRL+ALT+Del and select the Excel File Chooser and set it as active. Is there a way to make it always be the active dialogue box when it opens? Here's the code I'm using:
Sub UpdateLinks()
Dim sld As Slide
Dim sh As Shape
Dim strNms As String
Dim intI As Integer
Dim strNewPath
Dim ExcelFile
Dim exl As Object
Set exl = CreateObject("Excel.Application")
'Set exl = exl.ActiveWindow
'exl.Active = True
'Open a dialog box to promt for the new source file.
ExcelFile = exl.Application.GetOpenFilename(, , "Select Excel File")
'Go through every slide
For Each sld In ActivePresentation.Slides
For Each sh In sld.Shapes
If sh.Type = msoLinkedOLEObject Then
With sh.LinkFormat
strNms = .SourceFullName
intI = InStr(1, strNms, "!")
strNewPath = ExcelFile & Mid(strNms, intI, Len(strNms) - intI + 1)
.SourceFullName = strNewPath
End With
End If
Next sh
Next sld
ActivePresentation.UpdateLinks
End Sub
Thanks.
Suggestion: try this version of a file picker instead:
Sub FileDialogExample()
' Courtesy of John Wilson
' www.pptalchemy.co.uk
Dim fd As FileDialog
Dim sFilename As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
.Filters.Add "Excel Files", "*.xls, *.xlsx"
.InitialFileName = Environ("USERPROFILE") & "\Desktop\"
.AllowMultiSelect = False
If .Show = True Then sFilename = .SelectedItems(1)
End With
'do whatever with sFilename
MsgBox "You picked " & sFilename
End Sub
Here I have some VBA code that outputs a ton of files into Excel files. My question is, from this, is there anyway for it to Format the excel file a bit? What I would like to do is make the Columns bold and make the columns fit the size of the header as well.
Sub OutPutXL()
Dim qdf As QueryDef
Dim rs As DAO.Recordset
Set qdf = CurrentDb.QueryDefs("OutputStudents")
Set rs = CurrentDb.OpenRecordset("Teachers")
Do While Not rs.EOF
qdf.SQL = "SELECT * FROM Students WHERE contact='" & rs!contact & "'"
''Output to Excel
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, _
qdf.Name, "C:\Users\chrisjones\Documents\ProjectionsFY14\Teachers\" _
& rs!contact & ".xls", True
rs.MoveNext
Loop
End Sub
this is a quick and dirty combination of Phil.Wheeler's Code and my previous input, for me this is working. Don't forget to add Excel's Object Library in your Access-Macro.
Sub doWhatIWantTheDirtyWay()
pathToFolder = "C:\Users\Dirk\Desktop\myOutputFolder\"
scaleFactor = 0.9
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(pathToFolder)
For Each objFile In objFolder.Files
If objFso.GetExtensionName(objFile.path) = "xls" Then
Set objWorkbook = objExcel.Workbooks.Open(objFile.path)
For Each sh In objWorkbook.Worksheets
If sh.UsedRange.Address <> "$A$1" Or sh.Range("A1") <> "" Then
With sh
columncount = .Cells(1, 256).End(xlToLeft).Column
For j = 1 To columncount
With .Cells(1, j)
i = Len(.Value)
.ColumnWidth = i * scaleFactor
.Font.Bold = True
End With
Next
End With
End If
Next
objWorkbook.Close True
End If
Next
objExcel.Quit
End Sub
Yes it is possible! This is hacked together from one of my codes, might need a bit of editing before it works...
'This deals with Excel already being open or not
On Error Resume Next
Set xl = GetObject(, "Excel.Application")
On Error GoTo 0
If xl Is Nothing Then
Set xl = CreateObject("Excel.Application")
End If
Set XlBook = GetObject(filename)
'filename is the string with the link to the file ("C:/....blahblah.xls")
'Make sure excel is visible on the screen
xl.Visible = True
XlBook.Windows(1).Visible = True
'xl.ActiveWindow.Zoom = 75
'Define the sheet in the Workbook as XlSheet
Set xlsheet1 = XlBook.Worksheets(1)
'Then have some fun!
with xlsheet1
.range("A1") = "some data here"
.columns("A:A").HorizontalAlignment = xlRight
.rows("1:1").font.bold = True
end with
'And so on...
I have come across this problem a couple of times as well. As #Remou said, you will need to open excel to format xls files, this modification of your code silently opens Excel and that should get you in the right direction. Remember to add a reference to the Microsoft Excel Object Library in your VBA project.
Sub OutPutXL()
Dim qdf As QueryDef
Dim rs As DAO.Recordset
Dim xl as Excel.Application
Dim wb as Object
Dim strFile as string
Set qdf = CurrentDb.QueryDefs("OutputStudents")
Set rs = CurrentDb.OpenRecordset("Teachers")
Set xl = New Excel.Application
xl.DisplayAlerts = False
Do While Not rs.EOF
qdf.SQL = "SELECT * FROM Students WHERE contact='" & rs!contact & "'"
'Output to Excel
strFile = "C:\Users\chrisjones\Documents\ProjectionsFY14\Teachers\" & rs!contact & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, qdf.Name, strFile, True
'Start formatting'
Set wb = xl.Workbooks.Open(strFile)
With wb.Sheets(qdf.name)
'Starting with a blank excel file, turn on the record macro function'
'Format away to hearts delight and save macro'
'Past code here and resolve references'
End With
wb.save
wb.close
set wb = Nothing
rs.MoveNext
Loop
xl.quit
set xl = Nothing
End Sub
You could (depending on the number of files) make a template for each file you are outputting. In the long run if someone needs to change the formatting they can change the template which is going to be easier on you now that you don't have to sift through a bunch of excel formatting garbage. You could even let a qualified end user do it.
It's one of the biggest problems I have with excel sheets if I wrote the VBA I am responsible until I die for it. This way (in theory) they should be able to change a column, without changing how the data is outputted, just presented without you.
+1 To open the excel file itself and format it using that automation though.