Remove/ List all Keyboard Shortcuts VBA excel - vba

Someone in our office has assigned a macro to Ctrl+D. This is frustrating, as it already has a function in Excel.
Excel makes it easy for you to assign a macro in Developer> Macros, and I'm aware that if I push options in this menu I can see which keys are assigned where. The list of macros in this workbook is sizable, and I don't want to open each separately.
Is this listed anywhere? I assume there's a log with this somewhere? This is the closest I can find on msdn, but I need macros assigned in a macroworkbook: https://msdn.microsoft.com/en-us/library/hh179479(v=nav.90).aspx

Thanks to #GSerg for pointing this out, I will post this here for completeness to close the question. Source is here:
https://groups.google.com/forum/#!topic/microsoft.public.excel.worksheet.functions/TwcT-IlWjVk
To use this Macro (Sub), <alt-F8> opens the macro dialog box. Select the macro by name, and <RUN>.
===================================================
Option Explicit
'MUST set to Trust Access to the VBA Project Object Model
' in Excel Options
'Set reference to:
'Microsoft Visual Basic for Applications Extensibility
'Microsoft Scripting Runtime
'Microsoft VBScript Regular Expressions 5.5
Sub ListMacroShortCutKeys()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As CodeModule
Dim LineNum As Long
Dim ProcKind As VBIDE.vbext_ProcKind
Dim sProcName As String, sShortCutKey As String
Const FN As String = "C:\Temp\Temp.txt"
Dim S As String
Dim FSO As FileSystemObject
Dim TS As TextStream
Dim RE As RegExp, MC As MatchCollection, M As Match
Set RE = New RegExp
With RE
.Global = True
.IgnoreCase = True
.Pattern = "Attribute\s+(\w+)\.VB_ProcData\.VB_Invoke_Func = ""(\S+)(?=\\)"
End With
Set FSO = New FileSystemObject
Set VBProj = ActiveWorkbook.VBProject
For Each VBComp In VBProj.VBComponents
Select Case VBComp.Type
Case Is = vbext_ct_StdModule
VBComp.Export FN
Set TS = FSO.OpenTextFile(FN, ForReading, Format:=TristateFalse)
S = TS.ReadAll
TS.Close
FSO.DeleteFile (FN)
If RE.Test(S) = True Then
Set MC = RE.Execute(S)
For Each M In MC
Debug.Print VBComp.name, M.SubMatches(0), M.SubMatches(1)
Next M
End If
End Select
Next VBComp
End Sub
==============================

Press ALT+F11 goto your project module. You can find here shortcuts vba macro coding. if you want to keep it then no need to do otherwise you can select all and delete and save and close the file.

Related

Macro used to run on Outlook 2013, now doesn't run on Outlook 2021 on a new computer

A few years ago I had a developer write a macro for me to print the current email as two pages per page rather than on two separate pages.
It used to run successfully on my old computer Win 10/Outlook 2013.
I now have a new computer Win10/Outlook 2021
It now comes up with a compile error "User defined type not defined" for the line
Dim wdApp As Word.Application
I only have a rudimentary grasp of VBA so am unable to solve this one. Any help would be greatly appreciated.
Code is as follows:
Option Explicit
Public Sub print_mail()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim Response As Integer
Dim msg As String
Dim strSubject As String
Dim currentItem As Object
Set objOL = CreateObject("Outlook.Application")
Set objSelection = objOL.ActiveExplorer.Selection
For Each currentItem In objSelection
If currentItem.Class = olMail Then
Set objMsg = currentItem
PrintFirstPage objMsg
End If
Next
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
Public Sub PrintFirstPage(Mail As Outlook.MailItem)
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim olDoc As Word.Document
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Add(Visible:=True)
Set olDoc = Mail.GetInspector.WordEditor
olDoc.Range.Copy
wdDoc.Range.Paste
' With wdDoc
' .PageSetup.Orientation = wdOrientLandscape
' End With
'wdDoc.PrintOut
wdApp.PrintOut FileName:="", Range:=wdPrintRangeOfPages, Item:= _
wdPrintDocumentWithMarkup, Copies:=1, Pages:="1-2", PageType:= _
wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
PrintZoomColumn:=2, PrintZoomRow:=1, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
wdDoc.Close False
wdApp.Quit
End Sub
Use an untyped variable:
Dim appWD as Object
appWD = CreateObject("Word.Application")
Or try to add the Word object library reference to the project.
Inside the Visual Basic Editor , select Tools then References and scroll down the list until you see Microsoft Word 12.0 Object Library. Check that box and hit Ok.
VBA macros are not designed for distributing on multiple machines. If you need to deploy your code on a wide range of machines you would better consider transforming your solution to Office add-ins - it can be a COM add-in or a web-based one. See Walkthrough: Create your first VSTO Add-in for Outlook for more information.
When you move your VBA code to another machine you need to make sure that all COM references are added as it was on your original machine.
In order to solve your problem, you have to add the Word object library reference to your project.
Inside the Visual Basic Editor, select Tools then References and scroll down the list until you see Microsoft Word XX.0 Object Library. Check that box and hit Ok.
From that moment, you should have the auto complete enabled when you type Word. to confirm the reference was properly set.
Note, you could also use the late binding technology which doesn't require adding COM references:
' No reference to a type library is needed to use late binding.
' As long as the object supports IDispatch, the method can
' be dynamically located and invoked at run-time.
' Declare the object as a late-bound object
Dim oWord As Object
Set oWord = CreateObject("Word.Application")
' The Visible property is called via IDispatch
oWord.Visible = True
So, to start an Word Automation session, you can use either early or late binding. Late binding uses either the Visual Basic GetObject function or the CreateObject function to initialize Word. See Using early binding and late binding in Automation for more information.

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.

Excel VBA with Microstation Folder Search

i currently have this code in one of the macros for work. It is located under a button for browsing which folder to look into, and it will get the .DGNs and add them to a listbox.
I don't quite understand the code fully was hoping someone can give me a quick run down. Also, the code only looks at the selected folder for .DGNs, i want it to look into sub folders as well, is that possible?
Dim myFSO As New Scripting.FileSystemObject
Dim myFolder As Scripting.Folder
Dim myFile As Scripting.File
Dim myShell As New Shell32.Shell
Dim myRootFolder As Shell32.Folder3
Set myRootFolder = myShell.BrowseForFolder(0, "Pick", 0)
If myRootFolder Is Nothing Then Exit Sub
Set myFolder = myFSO.GetFolder(myRootFolder.Self.path)
txtCurrentFolder.Text = myRootFolder.Self.path
lstFilesInFolder.Clear
For Each myFile In myFolder.Files
Select Case UCase(Right(myFile.Name, 3))
Case "DGN"
If IsFileIn(myFile.path, lstFilesToProcess) = False Then
lstFilesInFolder.AddItem myFile.path
End If
End Select
Next
The code shows a GUI to select a folder, then iterates through the folder's child files testing if their names end in DGN and if so then testing if the file is already in some collection (lstFilesInFolder) and if not then adding it.
I think the approach seems a little complicated (picking a folder(s) can be done simply without using the Shell through Application.FileDialog) and I cannot judge some parts (like is it necessary to test lstFilesInFolder etc) without the rest of the code, and just personally I dislike the use of myX as a variable naming convention. Nevertheless, it does what it seems it is meant to do.
I like a stack/queue based approach to 'recursion' rather than actual recursive calls.
An example of converting your code to something that looks in subfolders as well is: (see comments on my added lines)
Dim myFSO As Scripting.FileSystemObject 'changed from late-binding
Set myFSO = New Scripting.FileSystemObject
Dim folderQueue As Collection 'queue
Set folderQueue = New Collection 'instantiate
Dim myFolder As Scripting.Folder
Dim subfolder As Scripting.Folder 'var for enumerating subfolders
Dim myFile As Scripting.File
Dim myShell As New Shell32.Shell
Dim myRootFolder As Shell32.Folder3
Set myRootFolder = myShell.BrowseForFolder(0, "Pick", 0)
If myRootFolder Is Nothing Then Exit Sub
folderQueue.Add myFSO.GetFolder(myRootFolder.Self.path) 'enqueue
Do While folderQueue.Count > 0 ''recursive' loop
Set myFolder = folderQueue(1) 'get next folder
folderQueue.Remove 1 'dequeue
txtCurrentFolder.Text = myRootFolder.Self.path
lstFilesInFolder.Clear
For Each subfolder in myFolder.SubFolders 'loop through subfolders adding for processing
folderQueue.Add subfolder 'enqueue
Next
For Each myFile In myFolder.Files
Select Case UCase(Right(myFile.Name, 3))
Case "DGN"
If IsFileIn(myFile.path, lstFilesToProcess) = False Then
lstFilesInFolder.AddItem myFile.path
End If
End Select
Next
Loop
As a final point, it is sometimes considered good practice to switch the use of a reference to a specific version of the Scripting library (nice for static typing) to using e.g. CreateObject("Scripting.FileSystemObject") before releasing to other users as the use of a reference can sometimes cause issues.

Import lines of code

Can we read scripts or lines of code to a module in vba? Like we have the include function in php.
For example:
We store this in Excel somewhere and call the range as xyz
line 1 of code
line 2 of code
line 3 of code
Then while running a macro we call this like
Sub my_macro()
xyz
End Sub
Basically I want to run a few lines of code repetitively but don't want to create another macro and pass the parameters.
This can be done using the Microsoft Visual Basic for Applications Extensibility 5.3 (VBIDE) library. There's some great examples at CPearson.com. I typically use this to insert snippets of code while I'm developing. I would personally be uncomfortable executing code stored in an excel sheet, but I tested this and it does work.
My worksheet:
A
1 MsgBox "I'm a test."
2 MsgBox "So am I."
I set up an empty subroutine that we will then insert into from the excel sheet.
Private Sub ProcToModify()
End Sub
And the subroutine that will actually insert the code into ProcToModify:
Sub ModifyProcedure()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim StartLine As Long
Dim NumLines As Long
Dim ProcName As String
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("Module1") ' specify module to modify
Set CodeMod = VBComp.CodeModule
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Set ws = ThisWorkbook.ActiveSheet 'change this accordingly
Set rng = ws.Range("A1:A2") 'and this
For Each cell In rng
ProcName = "ProcToModify"
With CodeMod
StartLine = .ProcStartLine(ProcName, vbext_pk_Proc)
NumLines = .ProcCountLines(ProcName, vbext_pk_Proc)
.InsertLines StartLine + NumLines - 2, cell.Value 'insert each line at the end of the procedure to get them in the correct order.
End With
Next cell
End Sub
Called at runtime like this:
Public Sub main()
ModifyProcedure
ProcToModify
End Sub
One Big Gotchya:
Before running this code, you need to go to Excel>>File>>Options>>Trust Center>>Trust Center Settings>>Macro Settings and check the "Trust access to the VBA project object model".
I would imagine that's because allowing access to the project object is a fairly concerning security risk.
From the cpearson.com site I linked to earlier:
CAUTION: Many VBA-based computer viruses propagate themselves by
creating and/or modifying VBA code. Therefore, many virus scanners may
automatically and without warning or confirmation delete modules that
reference the VBProject object, causing a permanent and irretrievable
loss of code. Consult the documentation for your anti-virus software
for details.

How to create and write to a txt file using VBA

I have a file which is manually added or modified based on the inputs. Since most of the contents are repetitive in that file, only the hex values are changing, I want to make it a tool generated file.
I want to write the c codes which are going to be printed in that .txt file.
What is the command to create a .txt file using VBA, and how do I write to it
Use FSO to create the file and write to it.
Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test"
oFile.Close
Set fso = Nothing
Set oFile = Nothing
See the documentation here:
http://technet.microsoft.com/en-us/library/ee198742.aspx
http://technet.microsoft.com/en-us/library/ee198716.aspx
Open ThisWorkbook.Path & "\template.txt" For Output As #1
Print #1, strContent
Close #1
More Information:
Microsoft Docs : Open statement
Microsoft Docs : Print # statement
Microsoft Docs : Close statement
wellsr.com : VBA write to text file with Print Statement
Office Support : Workbook.Path property
To elaborate on Ben's answer:
If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.
Here is a complete example module:
Option Explicit
' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()
Dim filePath As String
filePath = "C:\temp\MyTestFile.txt"
' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
' (Intellisense) work, which helps you avoid typos and lets you discover other useful
' methods of the FileSystemObject
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim fileStream As TextStream
' Here the actual file is created and opened for write access
Set fileStream = fso.CreateTextFile(filePath)
' Write something to the file
fileStream.WriteLine "something"
' Close it, so it is not locked anymore
fileStream.Close
' Here is another great method of the FileSystemObject that checks if a file exists
If fso.FileExists(filePath) Then
MsgBox "Yay! The file was created! :D"
End If
' Explicitly setting objects to Nothing should not be necessary in most cases, but if
' you're writing macros for Microsoft Access, you may want to uncomment the following
' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
'Set fileStream = Nothing
'Set fso = Nothing
End Sub
an easy way with out much redundancy.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Fileout As Object
Set Fileout = fso.CreateTextFile("C:\your_path\vba.txt", True, True)
Fileout.Write "your string goes here"
Fileout.Close
Dim SaveVar As Object
Sub Main()
Console.WriteLine("Enter Text")
Console.WriteLine("")
SaveVar = Console.ReadLine
My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)
Console.WriteLine("")
Console.WriteLine("File Saved")
Console.WriteLine("")
Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))
Console.ReadLine()
End Sub()