Using Word VBA to Update Excel Linked Chart Source - vba

I'm trying to set up a button in MS Word to update the linked Excel data source behind charts. I'll say upfront that I know this is easy with built-in functionality, but I'd like to use a button for those uncomfortable navigating the menus. Also, I've read and drawn from some great articles on this topic in general, but am getting an error not referenced in those pieces.
Testing has shown that Word a) identifies the Excel link as a field (vs a shape) and b) flags this field as type 87 (OCX). When I run the code below, it generates an "object variable or With block variable not set" error. However this appears to possibly be rooted in the field type based on this Microsoft article.
I'm struggling to find an alternative method and would appreciate help... this is my first foray into VBA for Word. Thanks!
Sub CommandButton1_Click()
Dim MyNewFile As Variant
Dim fDialog As FileDialog, result As Integer
Dim fieldCount As Integer
'Set up file dialog
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Select a file"
.Filters.Clear
.Filters.Add "Excel files", "*.xlsx,*.xlsb,*.xlsm,*.xls"
End With
'Show the dialog, store the file name
If fDialog.Show = -1 Then
MyNewFile = fDialog.SelectedItems(1)
End If
fieldCount = ActiveDocument.Fields.Count
For k = 1 To fieldCount
With ActiveDocument.Fields(k)
If .Type = 87 Then
With .LinkFormat
.SourceFullName = MyNewFile 'BLOWS UP HERE
.AutoUpdate = True
End With
End If
End With
Next k
End Sub

Related

Open Windows Explorer from Outlook to choose template [duplicate]

This question already has answers here:
Filepicker VBA to select file and store the file name not working
(2 answers)
Closed 3 years ago.
I am trying to write a macro that allows a user to select a .oft from a directory. I have been able to get a simple macro working that will open a specific .oft and modify the "from" field - this is what I have so far.
Sub EmailTemplateW10()
Set msg = Application.CreateItemFromTemplate("c:\test\test.oft")
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub
That works great, but there are numerous .oft files in the directory I am working with. I did find some articles that talk about setting up a toolbar with drop-downs and creating a macro for each .oft in the directory. I assume there has to be a better way than making a macro for each template.
I tried using this :
Sub EmailTemplateW10()
Set msg = Application.CreateItemFromTemplate(Demo)
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub
Function Demo()
Call Shell("explorer.exe" & " " & "C:\test\", vbNormalFocus)
End Function
Windows Explorer will come up - but the macro throws an error and stops when you acknowledge the error.
Is there perhaps some way to have the user select the file through explorer.exe and save the path of the selected file to a variable, and then pipe that into .CreateItemFromTemplate?
After some digging around I got this to work. I am obviously a VBA noob so i take no credit for the code - I was just able to mash it together and get it to work. Maybe someone in the future will find it helpful.
Public Function aBrowseForFile(aStartFolder As String) As String
On Error GoTo Err_txtBrowseForFile
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
Dim fDialog As Office.FileDialog
Dim varfile As Variant
Dim strPath As String
Dim strFilter As String, strFileName As String
Dim Main_Dir As String, DefFolder As String
Set fDialog = xlApp.Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.InitialView = msoFileDialogViewThumbnail
.AllowMultiSelect = False
.Title = "Please select one or more files"
.InitialFileName = aStartFolder
.InitialView = msoFileDialogViewThumbnail
.Filters.Clear
.Filters.Add "all files", "*.*"
If .Show = True Then
aBrowseForFile = .SelectedItems(1)
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
Exit_txtBrowseForFile:
Exit Function
Err_txtBrowseForFile:
MsgBox Err.Description, vbCritical, "MyApp"
Resume Exit_txtBrowseForFile
End Function
Sub EmailTemplateW10()
Dim MyFileURL As String
MyFileURL = aBrowseForFile("C:\users\")
Set msg = Application.CreateItemFromTemplate(MyFileURL)
msg.SentOnBehalfOfName = "user#domain.com"
msg.Display
Set msg = Nothing
End Sub

MSAccess - Run-time error '438': Object doesn't support this property or method

I'm running into an error when I attempt to add filters to a FileDialog.
I've tried to troubleshoot this with multiple posts / articles but nothing seems to have solved it. The online documentation identifies using .Filters.Add but it doesn't seem that .Filters is an appropriate method. .Filter.Add is at least recognized but is still invalid. .Filter.Clear is also recognized but is invalid as well.
Code:
Private Sub Command93_Click()
Dim objFD As Object, strOut As String
Set objFD = Application.FileDialog(2)
With objFD
.Filter.Clear
.Filter.Add "Excel File", ".xls"
If objFD.show = -1 Then
strOut = objFD.selecteditems(1)
End If
End With
Set objFD = Nothing
Me.txtSaveFile = strOut
Me.Refresh
End Sub
Ok here is the answer. First, thanks to the above shots at solving for the issue as they did lead to me reviewing the documentation (again) and making another attempt. The first answer put me on to the issue as .Filters simply won't work with a msoFileSaveAs dialog. However, you can't type in a different file name on an Open dialog (either 1 or 3).
So the answer is to use msoFileSaveAs or (2) and use the .Initialfilename property to set the extension which, in this case, will show a list of excel files which can be selected, or selected and modified and then you can click on "Save"
Working code:
Private Sub Command93_Click()
Dim objFD As Object
Dim strOut As String
Set objFD = Application.FileDialog(2)
With objFD
'.Filters.Clear
'.Filters.Add "Excel File", "*.xls; *.xlsx", 1
.Initialfilename = "*.xlsx"
If .show = -1 Then
strOut = objFD.selecteditems(1)
End If
End With
Set objFD = Nothing
Me.txtSaveFile = strOut
Me.Refresh
End Sub
Thanks all!
You are using the the filters with the wrong dialog box. .Filters will work with msoFileDialogOpen which has a value of 1 or with msofiledialogfilepicker which has a value of 3. So try .Filters with Application.FileDialog(1) or Application.FileDialog(3) as shown below and it will work but it will not work with the msofiledialogsaveas which has a value of 2
The constants msoFileDialogOpen and msoFileDialogSaveAs are not supported in Microsoft Access. What it doesn't mean: is that the Application.FileDialog is NOT suported. What it means: is the constants are not supported. If you type ?msoFileDialogOpen in Immediate Window in MS Access, you will not see any value and hence we have to pass those values literally or declare them.
You have to use .Filters instead of .Filter
See this example
Option Explicit
Const msoFileDialogOpen As Integer = 1
Sub Sample()
Dim f As Object
Dim i As Long
Set f = Application.FileDialog(msoFileDialogOpen)
With f
.Filters.Clear
.Filters.Add "Excel File", "*.xls*"
.AllowMultiSelect = True
If .Show Then
For i = 1 To .SelectedItems.Count
MsgBox .SelectedItems(i)
Next
End If
End With
End Sub
Screenshot
EDIT:
If you want to use Filters in while saving then check out the link Display Open and Save As Dialog Boxes in Access with API Functions
Here you will see how to use filters in the using the .SaveFileDialog using the CommonDialogAPI

Outlook VBA add hyperlink of chosen file in dialog

I'm trying to add the functionality in my Outlook (with VBA, I guess is easiest) to add a simple file dialog which takes the path of any files chosen and adds them to the email body as a hyperlink.
The idea of this is for network files to be shared amongst colleagues, instead of attaching them to the email, but just as easy to do.
This is my code so far, I can't even get the dialog to open, and I've had a good look at trying to get COMDLG32.ocx, so far I can't seem to make anything work.
Sub Main2()
Dim CDLG As Object
Set CDLG = CreateObject("MSComDlg.CommonDialog")
With CDLG
.DialogTitle = "Get me a File!"
.Filter = _
"Documents|*.doc|Templates|*.dot|Text Files|*.txt"
.ShowOpen
MsgBox .FileName
End With
Set CDLG = Nothing
End Sub
Thanks in advance, hopefully someone can show me how this is done!
Just for those who need it; OS Windows 10, Office 2010 H&B (yes, I know it's out of date :))
There seems to be no direct way to open a FileDialog in Outlook 2010 VBA.
The following macro (inspired by a related post) makes use of Excel to circumvent this:
Public Function promptFileName(title As String, filter As String) As String
' requires project reference to "Microsoft Excel 14.0 Object Library"
Dim xlObj As Excel.Application
Dim fd As Office.FileDialog
Dim name As String
Dim vItem As Variant
Dim filterArray() As String
Dim i As Integer
Set xlObj = New Excel.Application
xlObj.Visible = False
Set fd = xlObj.Application.FileDialog(msoFileDialogOpen)
name = ""
With fd
.title = title
.ButtonName = "Ok"
.Filters.Clear
filterArray = Split(filter, "|")
For i = LBound(filterArray) To UBound(filterArray) - 1 Step 2
.Filters.Add filterArray(i), filterArray(i + 1), 1 + i \ 2
Next i
If .Show = -1 Then
For Each vItem In .SelectedItems
name = vItem
Exit For
Next
End If
End With
xlObj.Quit
Set xlObj = Nothing
promptFileName = name
End Function
Private Sub testPromptFile
Dim name as String
name = promptFileName("a test", "Text Files (*.txt)|*.txt|All Files (*.*)|*.*")
MsgBox name
End Sub
Outlook 2013 and beyond provide an Office.FileDialog class for this purpose.
You can press a button with Outlook VBA.
Sub ExecuteMso_strId()
Dim objItem As Object
Dim strId As String
' Text appears when hovering over icon
' when adding buttons to a Quick Access toolbar or a ribbon
strId = "HyperlinkInsert"
On Error Resume Next
Set objItem = ActiveInspector.currentItem
On Error GoTo 0
If Not objItem Is Nothing Then
ActiveInspector.CommandBars.ExecuteMso (strId)
Else
ActiveExplorer.CommandBars.ExecuteMso (strId)
End If
End Sub
With this you do not have access to the parameters as with Excel.

MS Access 2010 - How can I tie an entry text box to a VBA command that opens a MS Word file based on user's entry?

Option Compare Database
Function Openword(conPath As String)
Dim appword As Word.Application
Dim doc As Word.Document
On Error Resume Next
Error.Clear
Set appword = GetObject(, "word.application")
If Err.Number <> 0 Then
Set appword = New Word.Application
appword.Visible = True
End If
Set doc = appword.Documents.Open(conPath, , True)
appword.Activate
Set doc = Nothing
Set appword = Nothing
End Function
Private Sub Command5_Click()
Dim mydoc As String
mydoc = "J:\3 - Client Services\1-Programs\12229709.docx"
Call Openword(mydoc)
End Sub
So far I have made the code that will open a specific file when the button on the form is clicked. However, there are a ton of these files that the user needs to be able to select and open. To keep it simple, I want them to be able to open the Word file by simply typing in the name of the file and clicking a button that will find and open it. The name of the file in the example above is simply 12229709.docx, but there are other files similar to it (e.g. 12172029, 12124057...) all in the same location. I want there to be a text box where the user can enter in the number and the button will check that specific folder for a file name with that number in it (without having to add the ".docx" if possible). How do I go about doing this?
EDIT - I forgot to mention that I cannot show the file path or use a file dialog box to allow the user to pick the file because the users that will be choosing the file do not have authorization to access this part of the network.
Try this out
Dim MyValue as Variant
MyValue = Inputbox("Enter File Name")
Dim MyDoc as String
MyDoc = "J:\3 - Client Services\1-Programs\" & MyValue & ".docx"
Call OpenWord(MyDoc)
Not sure if that is what you are looking for but I hope it helps.
I don't know why you'd want to make your user type in a file name when you can just open a file dialog and have them click on the right file.
Just put a command button on your form and include a line "Application.FollowHyperlink" plus this function name. The computer file associations can take care of the rest.
Sub Command()
Application.FollowHyperlink FileName()
End Sub
Public Function FileName() As String
Dim f As Object
' Must have object reference set to a MS Office Object Library for this to work.
Set f = Application.FileDialog(msoFileDialogFilePicker)
With f
.AllowMultiSelect = False
If .Show = -1 Then
FileName = .SelectedItems(1)
End If
End With
FileName = Nz(FileName, "")
End Function

Issue using FileDialog Application

I have a bit of code which I am trying to improve but having some issues.
The code is currently:
Sub TestListFilesInFolder()
'Workbooks.Add ' create a new workbook for the file list
' add headers
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker) ' Tried using a FileDialog Application but had no luck
With Range("A1")
.Formula = "Folder contents:"
.Font.Bold = True
.Font.Size = 12
End With
Range("A3").Formula = "Old File Path:"
Range("B3").Formula = "File Type:"
Range("C3").Formula = "File Name:"
Range("D3").Formula = "New File Path:"
Range("A3:H3").Font.Bold = True
ListFilesInFolder "L:\Pictures\A B C\B526 GROUP", True
' ListFilesInFolder fd, True ' I tried replacing the above line with this line but get an error
' list all files included subfolders
End Sub
Line 5 and 6 is a part I have added in where I am trying to get a file dialog to open where the user can choose the folder for the code to work on.
Also The commented out line near the bottom starting ListFilesInFolder is the one I tried inserting to replace the line above it.
The start of the next bit of code is:
Sub ListFilesInFolder(SourceFolderName As String, IncludeSubfolders As Boolean)
So it uses the folder and subfolders of that folder defined in the first sub.
Any help on this would be appreciated.
Regards,
Sam
You're passing fd as the first parameter to your ListFilesInFolder sub. This sub accepts a String as the first parameter, not a FileDialog.
Here's some sample code that, when executed, will open a file dialog and let the user select a folder. Once selected, it will print the path of the folder to B2. If no folder is selected (e.g. dialog is closed or canceled), B2 will contain the text No item selected.
I think you should create a new workbook and play around with this macro. Set a break point and walk through it, see what it's actually doing. Then you can alter it to make it work for your specific needs.
Public Sub SelectExportDestinationPath()
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then
sItem = "No item selected"
Else
sItem = .SelectedItems(1)
End If
End With
'if trailing slash is not found, add it
If Len(sItem) > 0 And InStr(Len(sItem), sItem, Application.PathSeparator, vbCompareText) = 0 Then
sItem = sItem & Application.PathSeparator
End If
Sheet1.Cells(2, 2).Value = sItem
Set fldr = Nothing
End Sub
make sure you have the appropriate reference picked:
Press Alt+F11 to open the VB Editor. In that window, choose menu items Tools -> References..., then look down the list for Microsoft Office XXX Object Library
It's 11.0 for Access 2003, 10.0 for Access 2002; 9.0 for Access 2000, 8.0 for Access 97 -- pick the right one.
Put a check mark in the box next to that reference, then close the dialog.
or, use the actual values, not the mso values
msoFileDialogOpen=1
msoFileDialogSaveAs=2
msoFileDialogFilePicker=3
msoFileDialogFolderPicker=4