Open file explorer and search for variable in textbox - vba

I the user to enter a keyword in a text box and when the macro is executed;
Open a new Windows' File Explorer window designated by a path.
path = C:\Users\ME\Desktop\Folder7
Search from the variable in SearchBox1 (this is a ActiveX text box on a worksheet.)
mySearch = sht.OLEObjects("SearchBox1").Object.Text & "*"
I saw multiple posts using Shell commands to open a File Explorer Window.
Call Shell("explorer.exe " & Chr(34) & "search-ms:query=*.pdf&crumb=location:C:\Users\ME\Desktop\Folder7" & Chr(34), vbNormalFocus)
When I run the above line there is an error from the explorer.
'Windows cannot find ". Make sure you typed the name correctly, and then try again.'
I need the macro to search for all files associated with the string. Folder names, file names, and words/characters within each type of document. They have all been OCR'd and Indexed by Windows.
It should have the ability to search for incomplete words as well.
I got Shell to open an explorer window to the path by
Call Shell("explorer.exe " & Chr(34) & "C:\Users\ME\Desktop\Folder7" & Chr(34), vbNormalFocus)
How can I search all folders and sub-folders within this freshly opened window?
I don't need the results compiled into Excel or any other program. I just need to make a quick search button as if you were to manually open this folder and use the search bar.

This worked for me:
Sub Tester()
ShowSearch "C:\_Stuff\test", "*.pdf" 'search by file name
ShowSearch "C:\_Stuff\Mail\", "reminder", True 'search by keyword
End Sub
Sub ShowSearch(searchWhere, searchFor, Optional SearchByKeyword As Boolean = False)
Const CMD As String = "explorer.exe ""search-ms:crumb=name:{query}&crumb=location:{location}"" "
Dim s
s = Replace(CMD, "{query}", WorksheetFunction.EncodeURL(searchFor))
s = Replace(s, "{location}", WorksheetFunction.EncodeURL(searchWhere))
If SearchByKeyword Then s = Replace(s, "crumb=name:", "crumb=")
'Debug.Print s
Shell s
End Sub
Note: WorksheetFunction.EncodeURL() is 2013 and later. For alternatives see:
How can I URL encode a string in Excel VBA?

Double Click on Cell to search
This is a solution I have combined from various places to open an explorer window at a path, that are filtered (searched) by the term in the selected cell using the windows File Explorer search function. It is triggered by a double click on a cell that contains the search term:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Application.Intersect(Target, Range("A1:AA1048576")) Is Nothing Then
Dim d As String
Dim searchpath As String
Dim searchlocation As String
Cancel = True
d = Selection.Value
'change window name to make sure new explorer window is opened for each instance
'copy string from manual search
searchpath = "search-ms:displayname=" & d & "%20Results%20&crumb=System.Generic.String%3A"
'copy string from manual search (e.g. my documents replace USERNAME)
searchlocation = "&crumb=location:C%3A%5CUsers%5CUSERNAME%5CDocuments"
If Not d = "" Then
Call Shell("explorer.exe """ & searchpath & d & searchlocation & "", 1)
'src: https://stackoverflow.com/questions/24376850/open-explorer-search-from-excel-hyperlink
End If
End If
End Sub
This opens the window in VbNormalFocus, with the window title set to the cell variable (d). The ensures that if this code is run on another cell value a new separate window will be opened. Without this I found the next time I ran the code the explorer window was not updated with the new search value, but just changed focus to the previous result.
edit: "copy from search bar" is the string after location: in the address bar of a manual search in explorer
Using ActiveX Controls
Add an ActiveX Text box (TextBox1) and button (CommandButton1) and add the following codeto the command button:
Private Sub CommandButton1_Click()
Dim d As String
Dim searchpath As String
Dim searchlocation As String
Cancel = True
d = TextBox1.Value
'change window name to make sure new explorer window is opened for each instance
'copy string from manual search
searchpath = "search-ms:displayname=" & d & "%20Results%20&crumb=System.Generic.String%3A"
'copy string from manual search (e.g. my documents replace USERNAME)
searchlocation = "&crumb=location:C%3A%5CUsers%5CUSERNAME%5CDocuments"
If Not d = "" Then
Call Shell("explorer.exe """ & searchpath & d & searchlocation & "", 1)
'src: https://stackoverflow.com/questions/24376850/open-explorer-search-from-excel-hyperlink
End If
End Sub
Now the user can change the text in the text box and clicking the button will open a windows file explorer search of the designated folder in the code.
Screenshot example using button search for "Editable Search Text"
EDIT
You can include additional search functions with the Windows search syntax:
http://download.microsoft.com/download/8/1/7/8174a74e-3d8d-4478-abc6-84cd51ad93c4/Windows_Desktop_Advanced_Query_Reference.pdf
Eg. you can search within the folder for all files with a partial match of each word in the string by changing the search variable "d:
...
d = Selection.Value
d = "(" & Replace(d, " ", " OR ") & ")"
...
if the selection (d) had a value of Where will I find it
This will search for (Where OR will OR I OR find OR it) in windows explorer and would return files with names such as WHEREver and Last WILL and testament. I've found this useful for qualitative information, where casting a wider search is acceptable and can be easily filtered through by the user (NOTE: the above example would also return all files with a name containing i so it is not very specific!)

executing Dir() empty after a Dir() with a given path will start to list all files in that dir, you just use if InStr() <> 0 to check against your value.
sFileName = Dir(path)
Do While sFileName > ""
tmp = tmp & sFileName & ";" : sFileName = Dir()
Loop
List() = Split(tmp, ";")
there you have a list of all files inside that path, you can check sub folders the same way by going through each one doing the same thing.

I do not take credit for the idea, it's awesome that you can do this. I just took the idea a step further and made it modular, so you can add any type of search:
Sub searchInExplorer_TEST()
'searchInExplorer "D:\", , , True, "*.jpg", True, "24 Feb 20"
searchInExplorer "D:\", , , , , True, "24 Feb 20", True, "picture"
End Sub
Sub searchInExplorer(searchWhere _
, Optional isSearchAll As Boolean, Optional strAll _
, Optional isSearchName As Boolean, Optional strName _
, Optional isSearchModified As Boolean, Optional strModified _
, Optional isSearchType As Boolean, Optional strType)
'*****************************************************
'https://stackoverflow.com/questions/52671500/vba-to-open-file-explorer-and-search-for-variable-in-textbox
'ALLOWS SEARCHING IN WINDOWS EXPLORER USING VARIABLES
'EITHER USE SEARCH ALL OR OTHER SEARCH TIMES
'EACH SEARCH TYPE HAS AN ON/OFF SWITCH AND A STRING VARIABLE TO SEARCH BY
'*****************************************************
Dim STR As String
STR = "explorer.exe ""search-ms:"
If isSearchAll Then
STR = STR & "crumb=:" & WorksheetFunction.EncodeURL(strAll)
Else
If isSearchName Then
STR = STR & "&crumb=name:" & WorksheetFunction.EncodeURL(strName)
End If
If isSearchModified Then
STR = STR & "&crumb=modified:" & WorksheetFunction.EncodeURL(strModified)
End If
If isSearchType Then
STR = STR & "&crumb=kind:" & WorksheetFunction.EncodeURL(strType)
End If
End If
STR = STR & "&crumb=location:" & WorksheetFunction.EncodeURL(searchWhere)
STR = STR & """ "
Debug.Print STR
Shell STR
End Sub

Related

Insert an image file in a MAC Word Userform

I am not a programmer so not sure what to do here. I would like an option of adding an image file in a Microsoft Word document userform for MAC. I had used a code earlier which works perfectly in Windows but it doesnt work for MAC and gives a 5948 error. I had added a field for the image in the userform with a button to add the image and the final submit button. The add button should allow the user to insert any size image from the local folder.
The code I was using is given below:
Dim ImagePath As String
Private Sub CMDAddImage_Click()
Dim objFileDialog As Office.FileDialog
Set objFileDialog = Application.FileDialog(MsoFileDialogType.msoFileDialogFilePicker)
With objFileDialog
.AllowMultiSelect = False
.ButtonName = "File Picker"
.Title = "File Picker"
If (.Show > 0) Then
End If
If (.SelectedItems.Count > 0) Then
Call MsgBox(.SelectedItems(1))
ImagePath = .SelectedItems(1)
End If
End With
Image1.Picture = LoadPicture(ImagePath)
End Sub
And the code in submit button was:
Dim objWord
Dim objDoc
Dim objShapes
Dim objSelection
'Set objSelection = ActiveDocument.Sections
'objSelection.TypeText (vbCrLf & "One Picture will be inserted here....")
ActiveDocument.Bookmarks("Field04").Select
Set objShapes = ActiveDocument.InlineShapes
objShapes.AddPicture (ImagePath)
End
End Sub
Can someone please help me edit the code for mac. In mac it does not allow to add the file.
You should check out the suggestion made by #JohnKorchok in a comment to your previous question - insert an image Content Control in your document instead, and throw away the VBA.
But if you need to keep using VBA and a UserForm...
Application.FileDialog is not available on Mac.
Application.GetOpenFileName is not avaialble from Word (it's an Excel thing).
Application.Dialogs does not do the same thing as GetOpenFileName so the user experience will be rather different, but at its simplest, you can use it like this:
With Application.Dialogs(wdDialogFileOpen)
' .Display = -1 for "OK" ("Open" in this case)
' .Display = 0 for "Cancel"
' (THere are other possible return values
' but I do not think they are applicable here)
If .Display = -1 Then
ImagePath = .Name
End If
End With
or if you prefer, the lengthier
Dim dlg As Word.Dialog
Set dlg = Application.Dialogs(wdDialogFileOpen)
With dlg
If .Display = -1 Then
ImagePath = .Name
End If
End With
Set dlg = Nothing
However, this dilaog does not let you specify file types or any kind of filtering, a starting folder etc. Attempts to set Finder search criteria via something like
.Name = "(_kMDItemFileName = ""*.jpg"")"
.Update
before the .Display either can't work or need different syntax.
Further, the Apple dialog may start with its
own filtering set up so the user will have to click Options to enable All Files. You don't know what file type the user will choose so you will need to deal with that.
An alternative is to invoke Applescript. For this, it appears that you can still use the VBA MacScript command, which means that you can put all the script in your VBA file. If that does not work, then unfortunately you have to use AppleScriptTask which would require you to work some more on the Script and install the script in the correct folder on every Mac where you need this feature.
Here's the code I used - you would probably need to wrap everything up in another function call and use conditional compilation or other tests to call the correct routine depending on whether the code is running on Mac or Windows
Private Sub CMDAddImage_Click()
Dim s As String
Dim sFileName As String
On Error Resume Next
s = ""
' set this to some other location as appropriate
s = s & "set thePictureFoldersPath to (path to pictures folder)" & vbNewLine
s = s & "set applescript's text item delimiters to "",""" & vbNewLine
s = s & "set theFile to ¬" & vbNewLine
' add the image file types you want here
s = s & "(choose file of type {""png"",""jpg""} ¬" & vbNewLine
s = s & "with prompt ""Choose an image to insert."" ¬" & vbNewLine
s = s & "default location alias thePictureFoldersPath ¬" & vbNewLine
s = s & "multiple selections allowed false) as string" & vbNewLine
s = s & "set applescript's text item delimiters to """"" & vbNewLine
' choose file gives as an AFS path name (with colon delimiters)
' get one Word 2016/2019 will work with
s = s & "posix path of theFile"
sFileName = MacScript(s)
If sFileName <> "" Then
' Maybe do some more validation here
ImagePath = sFileName
Image1.Picture = LoadPicture(ImagePath)
End If
End Sub

FileSave() Word Macro

I have written a macro which when a file is created and the little save button is clicked the macro is triggered(as it overrides the default FileSave function). The macro extracts information from a table in my document, converts it to a string then cleanses that string of any carriage returns then uses that as the file name. An if statement then runs checking whether a hidden row in the table has a value of 1 and if not then it will set the value to 1 and save the document at the location specified with the new filename.
All of this works great except when I re-open the file to edit it, as my users will do, and click save again it tries to run everything again, completely ignoring my If statements first statement and will add a carriage return to the start of the filename effectively breaking the save function to SharePoint as it has an invalid character in it. If you then click save again it will seemingly run the macro as normal and save it by actually reading the if statement correctly. Am I doing something wrong here?
Here is the code:
Sub FileSave()
Dim strText As String
Dim strClean As String
Dim strFileName As String
Dim strLocation As String
Dim strSavedName As String
Dim strCleanSave As String
strText = ActiveDocument.Tables(1).Rows(1).Cells(2).Range.Text
strClean = Application.CleanString(strText)
strFileName = strClean + "_" + Format(Date, "yyyy-mm-dd")
strLocation = "[My SharePoint Site]"
If ActiveDocument.Tables(1).Rows(1).Cells(3).Range.Text = "1" Then
strSavedName = ActiveDocument.Name
strCleanSave = Application.CleanString(strSavedName)
ActiveDocument.SaveAs FileName:=strSavedName
Exit Sub
Else
ActiveDocument.Tables(1).Rows(1).Cells(3).Range.Text = "1"
ActiveDocument.SaveAs FileName:=strLocation & strFileName & ".docx"
End If
End Sub
Word table cell text ranges are terminated with two hidden chars, a carriage return (ASCII 13) and a bell (ASCII 7). Your IF condition returns false because it is testing the equivalence of "1" and "1" & Chr(13) & Chr(7).
In your case you can limit the test to the first char:
If Left$(ActiveDocument.Tables(1).Rows(1).Cells(3).Range.Text, 1) = "1" Then
More generally you can test the visible cell contents with a Len() - 2.
Hope that helps.

Creating Subfolders in VB2010?

I'm in the position of needing to make a bunch of folders for my PC so I decided to turn it in to a coding task. I've managed to make it so the user types in the location they want the folders to go into as well as each line of the other text box being the title for a new folder.
Here's the problem. I ideally would like to put multiple folders inside each folder without running the program again. The textbox would look something like this and would result in file 1,2 in folderA and file 3,4 in folderB;
FolderA
File 1
File 2
FolderB
File 3
File 4
Here is the code I've done so far.
Dim Address As String = TextBox1.Text
For i As Integer = 0 To RichTextBox1.Lines.Count - 1
My.Computer.FileSystem.CreateDirectory(Address + (RichTextBox1.Lines(i)))
Next
Do you know what I would have to add to my code so that it includes sub-folders?
(I haven't been learning long so I'm sorry if the answer is really obvious.)
#punintentional
The code below will do exactly what you asked for. You HAVE to make sure you have a reference set to the Microsoft Office Object Library. You do this by going to Tools>References and find the appropriate on. I designed the below code with Microsoft Office 12 Object Library. If you are using Office 2010, I think the Reference will be for Microsoft Office 14 Object Library.
Option Explicit
Public Sub DirectorySelect()
Dim diaFileDialog As FileDialog
Dim blDirSelected As Boolean
Dim strBaseDirectory As String
Dim strA_Dir As String
Dim StrB_Dir As String
' set up a MS Office file dialog box to select a folder/directory
Set diaFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
With diaFileDialog
.AllowMultiSelect = False ' user may only select one base folder
.Title = "Select the base director" ' title of the dialog box
blDirSelected = .Show ' the .show method will return false if the user does not select a directory
If blDirSelected = True Then ' a directory was selected
strBaseDirectory = .SelectedItems(1) ' put the directory into a variable
strBaseDirectory = strBaseDirectory & "\" ' the returned directory needs a trailing backslash
' These steps will jump to the other sub procedure to make the desired folders
MakeNewDir _
BaseDirectory:=strBaseDirectory, _
AddDirectory:="FolderA"
strA_Dir = strBaseDirectory & "FolderA" & "\"
MakeNewDir _
BaseDirectory:=strA_Dir, _
AddDirectory:="Folder1"
MakeNewDir _
BaseDirectory:=strA_Dir, _
AddDirectory:="Folder2"
MakeNewDir _
BaseDirectory:=strBaseDirectory, _
AddDirectory:="FolderB"
StrB_Dir = strBaseDirectory & "FolderB" & "\"
MakeNewDir _
BaseDirectory:=StrB_Dir, _
AddDirectory:="Folder3"
MakeNewDir _
BaseDirectory:=StrB_Dir, _
AddDirectory:="Folder4"
End If
End With
End Sub
Public Sub MakeNewDir(ByVal BaseDirectory As String, ByVal AddDirectory As String)
If Dir(BaseDirectory, vbDirectory) = vbNullString Then
MkDir BaseDirectory
End If
If Right(BaseDirectory, 1) <> "\" Then
BaseDirectory = BaseDirectory & "\"
End If
MkDir BaseDirectory & AddDirectory
End Sub

How to prevent free distribution of a commercial Excel spreadsheet

I'm not sure if this is more appropriate under a different SE site (Super User?).
I want to build and sell a complex macro driven driven spreadsheet to a certain vertical. I am mainly concerned about free/unauthorised distribution between customers within that vertical.
I can see that there is a few obscure products on the market that might be able to do what I want, but the few reviews that i've been able to find haven't been favourable.
One vendor however lists that free distribution can circumvented by either:
Using a key generator to create license codes
Using the online activation feature
Or by simply using an encrypted password
Is anyone aware of any guidelines/frameworks (any language) for me to build my own solution to achieve this, namely requiring licence codes or online activation?
If this is generally a difficult endeavour, is there a commercial product that anyone recommend?
I'm also thinking the complexities involved in achieving this might push me to building a small SaaS application instead. Am I better off just going that route?
I have created an Excel sheet that I could remotely remove access to if a monthly subscription payment failed. Here is how to accomplish this:
Create and HTML table and upload it to your website
Within your Excel doc go to the data tab and select get from web - import your table into a sheet called "Verify" - make sure your table has 3 columns. Serial Number is in the first column, description of user in 2nd, and your error message in the top of col 3. The error message stored here is what every user that isn't registered will see. The first serial number should appear in cell A2 of the sheet Verify.
Within your Visual Basic editor paste this code into a Module - This code will return an 8 digit serial number based on a PC's Hard Drive serial number:
Function HDSerialNumber() As String
Dim fsObj As Object
Dim drv As Object
Set fsObj = CreateObject("Scripting.FileSystemObject")
Set drv = fsObj.Drives("C")
HDSerialNumber = Left(Hex(drv.SerialNumber), 4) _
& "-" & Right(Hex(drv.SerialNumber), 4)
End Function
Also in another module I make sure the Internet is connected. If no Internet then the sheet closes. If you don't do this then if someone disconnects from the Internet your serials won't be loaded.
Option Explicit
#If VBA7 And Win64 Then
Private Declare PtrSafe Function InternetGetConnectedStateEx Lib "wininet.dll" (ByRef lpdwFlags As Long, ByVal lpszConnectionName As String, ByVal dwNameLen As Integer, ByVal dwReserved As Long) As Long
#Else
Private Declare Function InternetGetConnectedStateEx Lib "wininet.dll" (ByRef lpdwFlags As Long, ByVal lpszConnectionName As String, ByVal dwNameLen As Integer, ByVal dwReserved As Long) As Long
#End If
Function IsInternetConnected() As Boolean
Dim strConnType As String, lngReturnStatus As Long, MyScript As String
If Application.OperatingSystem Like "*Macintosh*" Then
MyScript = "repeat with i from 1 to 2" & vbNewLine
MyScript = MyScript & "try" & vbNewLine
MyScript = MyScript & "do shell script ""ping -o -t 2 www.apple.com""" & vbNewLine
MyScript = MyScript & "set mystatus to 1" & vbNewLine
MyScript = MyScript & "exit repeat" & vbNewLine
MyScript = MyScript & "on error" & vbNewLine
MyScript = MyScript & "If i = 2 Then set mystatus to 0" & vbNewLine
MyScript = MyScript & "end try" & vbNewLine
MyScript = MyScript & "end repeat" & vbNewLine
MyScript = MyScript & "return mystatus"
If MacScript(MyScript) Then IsInternetConnected = True
Else
lngReturnStatus = InternetGetConnectedStateEx(lngReturnStatus, strConnType, 254, 0)
If lngReturnStatus = 1 Then IsInternetConnected = True
End If
End Function
Then inside the Workbook_Open area paste this:
Private Sub Workbook_Open()
If IsInternetConnected Then
Dim objFSO As Object
Dim MyFolder As String
Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim trialstartdate As String
Dim z As String
Dim fsoFSO
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
'UNCOMMENT below to SHOW the serials sheet when the workbook is opened
ActiveWorkbook.Sheets("Verify").Visible = xlSheetVisible
'UNCOMMENT below to hide the serials sheet when the workbook is opened
'ActiveWorkbook.Sheets("Verify").Visible = xlSheetVeryHidden
Refresh_Serials
z = 2
'loop here for valid hard drive serial number
Do Until IsEmpty(Worksheets("Verify").Cells(z, 1).Value)
If Worksheets("Verify").Cells(z, 1).Value = HDSerialNumber Then
'verified and let pass
GoTo SerialVerified
End If
z = z + 1
Loop
Dim custommessage As String
custommessage = Worksheets("Verify").Cells(2, 3)
MsgBox custommessage + " Your serial number is: " + HDSerialNumber
Dim wsh1, MyKey1
Set wsh1 = CreateObject("Wscript.Shell")
MyKey1 = "%{TAB}"
wsh1.SendKeys MyKey1
MsgBox "The Commission Tracker will not open without a valid serial number. It will now close. uncomment this in workbook->open to close the workbook if the serial isn't found"
Application.DisplayAlerts = False
'uncomment this to close the workbook if the serial isn't found
'ActiveWorkbook.Close
Application.DisplayAlerts = True
SerialVerified:
' does the end user agree to not use this tool for mailicous purposes?
MsgAgree = MsgBox("Your PC's serial number is " & HDSerialNumber & ". By clicking 'Yes' you agree to use our software as described in our end user agreement. - the URL to your terms here", vbYesNo, "Final Agreement")
If MsgAgree = vbNo Then
'close program
MsgBox "This program will now close since you do not agree to our end user agreement"
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
Else
'continue to open the program
End If
Else
MsgBox "No Network Connection Detected - You must have an internet connection to run the commission tracker."
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End If
End Sub
That should do it....
Create your own special unique license keys in a macro that will unlikely be generated in a key generator. Add your own prefix, for example. You could store if a user is using it in an online database. Downfall to this solution is that the users would have to be connected to the outside internet.
Then lock down that module with the keys by the following:
To protect your code, open the Excel Workbook and go to Tools>Macro>Visual Basic Editor (Alt+F11). Now, from within the VBE go to Tools>VBAProject Properties and then click the Protection page tab and then check "Lock project from viewing" and then enter your password and again to confirm it. After doing this you must save, close & reopen the Workbook for the protection to take effect.

FileDialog in Word 2011 VBA

I'm hoping for a bit of a sanity check. I'm adapting a Word add-in (written in VBA for Word 2010) for Mac, specifically, at this point, Word 2011. I'm aware of many of the differences, but one that I haven't been able to find much documentation on is the apparent lack of FileDialog. The closest I've come to an answer is here: http://www.rondebruin.nl/mac.htm where the author uses Application.GetOpenFilename. That method doesn't seem to exist for Word, though (the focus of that site is Excel).
Does anyone know how to use the file and folder picker dialogs that FileDialog makes available? I'm not familiar with Applescript, really, but I've had to learn a little in order to get around Word 2011's funky file management issues (Dir, FileCopy, etc.). So, if that's the answer, any sense of what the code might look like in Applescript would be greatly appreciated. (I more or less know how to translate that into VBA).
I believe you have to use Apple Script in order to do this a bit better on the Mac. The following code allows the user to select text files which is returned as an array from the function. You would simply be able to modify the Apple Script to return other file types and select directories, I'll leave that to you.
The code that calls the function and displays a message box with all the files:
Sub GetTextFilesOnMac()
Dim vFileName As Variant
'Call the function to return the files
vFileName = Select_File_Or_Files_Mac
'If it's empty then the user cancelled
If IsEmpty(vFileName) Then Exit Sub
'Loop through all the files specified
For ii = LBound(vFileName) To UBound(vFileName)
MsgBox vFileName(ii)
Next ii
End Sub
And the function that does the Apple Script work:
Function Select_File_Or_Files_Mac() As Variant
'Uses AppleScript to select files on a Mac
Dim MyPath As String, MyScript As String, MyFiles As String, MySplit As Variant
'Get the documents folder as a default
On Error Resume Next
MyPath = MacScript("return (path to documents folder) as String")
'Set up the Apple Script to look for text files
MyScript = "set applescript's text item delimiters to "","" " & vbNewLine & _
"set theFiles to (choose file of type " & " {""public.TEXT""} " & _
"with prompt ""Please select a file or files"" default location alias """ & _
MyPath & """ multiple selections allowed true) as string" & vbNewLine & _
"set applescript's text item delimiters to """" " & vbNewLine & _
"return theFiles"
'Run the Apple Script
MyFiles = MacScript(MyScript)
On Error GoTo 0
'If there are multiple files, split it into an array and return the results
If MyFiles <> "" Then
MySplit = Split(MyFiles, ",")
Select_File_Or_Files_Mac = MySplit
End If
End Function
Finally, it can be a bit of a pain specifying different file types, if you want to specify only Word documents, then replace public.TEXT with com.microsoft.word.doc, however this won't allow .docx or .docm files. You need to use org.openxmlformats.wordprocessingml.document and org.openxmlformats.wordprocessingml.document.macroenabled respectively for these. For more info on these see: https://developer.apple.com/library/mac/#documentation/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html