I have found the Macro for MS Word (as below) from the website https://excelchamps.com/blog/vba-code-search-google-chrome/
Sub GoogleSearch()
Dim chromePath As String
Dim search_string As String
Dim query As String
query = InputBox("Please enter the keywords", "Google Search")
search_string = query
search_string = Replace(search_string, " ", "+")
chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Shell (chromePath & " -url http://www.google.com/search?hl=en&q=" & search_string)
End Sub
It is expected that:
I press the Macro button, the InputBox pop-out, then I type keywords and it automatically opens Chrome to search those keywords.
If I press the Macro button mistakenly, then I press "Cancel" or "X" to close the Inputbox, Chrome will not automatically open.
I added if msgboxresult = "" then exit sub in the middle of the code. When I open the Inputbox and close it, Chrome doesn't open. But whatever I typed in the Inputbox, Chrome doesn't open and no search is conducted.
Does anyone know what codes should add to it in order to make it End Sub when I don't type anything and close the Inputbox?
Whilst (StrPtr(query) = 0) will indicate that the user pressed cancel it will not catch when the user has left the search term blank and clicked OK.
A better way of writing your routine is to ignore whether the user cancelled and check whether you have a search term to google. Simply checking that query isn't a zero length string before proceeding to launch chrome will catch both eventualities.
Sub GoogleSearch()
Const chromePath As String = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Dim query As String
query = InputBox("Please enter the keywords", "Google Search")
If Not query = vbNullString Then
query = Replace(query, " ", "+")
Shell (chromePath & " -url http://www.google.com/search?hl=en&q=" & query)
End If
End Sub
Related
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
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
Say you want to have a button that the user can click and save a copy of the current file as a PDF(Documentation):
Application.ActiveDocument.SaveAs2 fileName:="fileName.pdf", FileFormat:=wdFormatPDF
This works fine, the user is presented with a save dialog, selects a location and the file is saved, however a few things are not correct:
The type displayed does not match what was specified in the VBA, how can this be correct? It still saves as type "PDF" without issue, even after showing "DOCX" as the file type in the "Save as Type" drop down. Also the "fileName.pdf" is not placed in the "File Name" box, its as if the dialog box is unaware of the options set in the VBA code(This same issue is also referenced in this post).
UPDATE 1
After taking a second look at my code I now realize that the SaveAs2 Method was not displaying the dialog menu, the correct version of the code(simplified) can be described as:
Dim selected As String: selected = Application.FileDialog(msoFileDialogSaveAs).Show()
Dim filePath As String
If selected <> 0 Then
filePath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
Application.ActiveDocument.SaveAs2 fileName:=Split(filePath, ".")(0), FileFormat:=wdFormatPDF
End If
So then the real question(I guess) is how do you get "Application.FileDialog" to display the proper type you wish to save in under the "Save as type" drop down, and this has already been answered by #PatricK. Thanks everyone for the help, I apologize for the initial confused nature of this question.
I am surprised for SaveAs2 will bring you a prompt to be honest - Only a new document and .Save will bring you that prompt.
If you want to get something similar to that prompt, you use Application.FileDialog with type msoFileDialogSaveAs.
Use this code below (perhaps as an AddIn suits more):
Option Explicit
Sub MySaveAs()
Dim oPrompt As FileDialog, i As Long, sFilename As String
Set oPrompt = Application.FileDialog(msoFileDialogSaveAs)
With oPrompt
' Find the PDF Filter from Default Filters
For i = 1 To .Filters.Count
'Debug.Print i & " | " & .Filters(i).Description & " | " & .Filters(i).Extensions
' Locate the PDF filter
If InStr(1, .Filters(i).Description, "PDF", vbTextCompare) = 1 Then
.FilterIndex = i
Exit For
End If
Next
' Change the title and button text
.Title = "Saving """ & ActiveDocument.Name & """ to PDF format"
.ButtonName = "Save to PDF"
' Default name
.InitialFileName = ActiveDocument.Name
' Show the Prompt and get Filename
If .Show = -1 Then
sFilename = .SelectedItems(1)
Debug.Print "Final filename: " & sFilename
' Save the file as PDF
ActiveDocument.SaveAs2 sFilename, wdFormatPDF
End If
End With
Set oPrompt = Nothing
End Sub
Screenshot sample:
I am making a program that will format flash drives that are selected by the user. For this I am using the format.com process and sending the "Enter" key so the process will be fully automatic. For this to work correctly, I delay the press of the "Enter" key by half a second to ensure it is being sent to the command prompt. For some reason, one command prompt window opens briefly and then closes which seems to create an issue with the second command I am trying to execute where files will then be copied from another flash drive to the formatted ones. Visual Basic completely freezes and the only way to gain control is by hitting Ctrl + Alt + Del. I even have the copying being delayed by 20 seconds to ensure the formatting process is complete. Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs)
'Variables initialized
Dim i As Integer
Dim DrvsToFormat As String
'Stores all selected drives in an array named "drives" and creates string with drive letter
Dim drives(ListBox1.SelectedItems.Count) As String
For i = 0 To ListBox1.SelectedItems.Count - 1
drives(i) = ListBox1.SelectedItems(i).ToString.Substring(0, 2)
If i = Not drives.Length Then
DrvsToFormat = DrvsToFormat & " " & drives(i) & ","
Else
DrvsToFormat = DrvsToFormat & " " & drives(i)
End If
Next
'Gets the current date and formats it as "mm-dd"
Dim currentDate As Date = Date.Today()
Dim formattedDate As String = currentDate.ToString("MM-dd")
'Prompts the user to ensure they wish to format the drives
Dim response = MessageBox.Show("Are you sure you want to format drive(s) " & DrvsToFormat & "? All data will be lost.", "WARNING!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If response = MsgBoxResult.Yes Then
'Iterates through all selected drive, performs quick format as NTFS, and names the drive with the current date
'Sends enter key in order to continue formatting in cmd prompt
For i = 0 To drives.Length - 1
Process.Start("format.com", drives(i) & "/Q /FS:NTFS /V:" & formattedDate)
Threading.Thread.Sleep(500)
SendKeys.Send("{ENTER}")
Threading.Thread.Sleep(20000)
Process.Start("cmd.exe", "Xcopy " & MasterFD.masterDrive & " " & drives(i) & "/e ")
Next
End If
End Sub
In MS Access I want to print a preselection of pages but I want the user to select the output printer.
I already tried the PrintOut and acCmdPrint commands but I want a mix of them.
If I use the PrintOut command I have the option to set in the parameters the page range but the dialog box doesn't show up and the document gets printed to the default printer. Can´t give the option to select the printer this way.
If I use the acCmdPrint command I do't have an option to preselect the pages. The range of the full document appears in the page selection (ex 1 to final page) and I want to select 1 to 3 or 5 to 9 instead of 1 to final page. The good part is that user gets the option to select the printer this way.
Printer and page selection? Any help? Thanks.
Maybe you can try to do the following: Just do a print preview rather than a print, then while viewing the report, the user should be able to select File, Print..., which will bring up the options he wants like page range.
DoCmd.OpenReport "report", acViewPreview
DoCmd.RunCommand acCmdPrint
Update 1: You can invoke a printer selection dialog using xlDialogPrinterSetup
Dim myprinter As String
' Back up default printer.
myprinter = Application.ActivePrinter
' Let the user select a printer.
If Application.Dialogs(xlDialogPrinterSetup).Show Then
' Print to the selected printer
cmd.PrintOut Preview:=False, ActivePrinter:=Application.ActivePrinter
End If
' Restore original printer.
Application.ActivePrinter = myprinter
Update 2: Ok, If it is Access it seems that xlDialogPrinterSetup it is not available. One option is that you can create your own Print Dialog Form using the following code that lists all the available printers. The code was taken from this link.
Sub ShowPrinters()
Dim strCount As String
Dim strMsg As String
Dim prtLoop As Printer
On Error GoTo ShowPrinters_Err
If Printers.Count > 0 Then
' Get count of installed printers.
strMsg = "Printers installed: " & Printers.Count & vbCrLf & vbCrLf
' Enumerate printer system properties.
For Each prtLoop In Application.Printers
With prtLoop
strMsg = strMsg _
& "Device name: " & .DeviceName & vbCrLf _
& "Driver name: " & .DriverName & vbCrLf _
& "Port: " & .Port & vbCrLf & vbCrLf
End With
Next prtLoop
Else
strMsg = "No printers are installed."
End If
' Display printer information.
MsgBox Prompt:=strMsg, Buttons:=vbOKOnly, Title:="Installed Printers"
ShowPrinters_End:
Exit Sub
ShowPrinters_Err:
MsgBox Prompt:=Err.Description, Buttons:=vbCritical & vbOKOnly, _
Title:="Error Number " & Err.Number & " Occurred"
Resume ShowPrinters_End
End Sub
You only need to adapt that code to fill a listbox in your own print dialog form. And then, when the user selects one of the printers, you can do the following:
Dim oldPrinter As Printer
' Save original printer.
Set oldPrinter = Application.Printer
' x is the list index of the selected printer of your form.
Application.Printer = Application.Printers.Item(x)
' Print the report here using PrintOut.
' Restore the printer.
Application.Printer = oldPrinter