21 | 08 | 2017

Run VBA code from Shortcut Key

Recently somebody asked if it was possible to insert a block with a shortkey. I thought that that was a good question and for that reason the code below is showing how to realize this.


To make the shortkey happen we first have to create a VBA routine we can call from a shortkey. I took the InsertBlockS below as a sample.

{code lang:vbnet lines:false hidden:false}
Private Sub InsertBlockS()

InsertBlock "C:\Block.dwg", 0
'Change the 0 to another value (in degrees) to rotate the block'
End Sub


Function InsertBlock(ByVal blockpath As String, ByVal rotation As Double)

Dim blockobj As AcadBlockReference
Dim insertionPnt As Variant
Dim prompt1 As String

'set rotation Angle
rotateAngle = rotation
rotateAngle = rotation * 3.141592 / 180#

'Prompt is used to show instructions in the command bar
prompt1 = vbCrLf & "Enter block insert point: "

ThisDrawing.ActiveSpace = acModelSpace

insertionPnt = ThisDrawing.Utility.GetPoint(, prompt1)

Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock(insertionPnt, blockpath, 1#, 1#, 1#, rotateAngle)

End Function{/code}

Put this code above into a module called Blocks. Then save the project to C:\TestProject.dvb.

Now that the project is created we can create a COMMAND to run it from the Commandline. To do so we have to add the following LISP code to Acadxxxx.lsp (xxxx stand for the AutoCad version, for instance Acad2000.lsp). The AutoCadxxxx.lsp file is located at C:\Program Files\AutoCad xxxx\Support\Acadxxxx.lsp

{code lang:vbnet lines:false hidden:false}Defun C:INSERTBLOCK ()

(vl-vbarun "C:\\TestProject.dvb!Blocks.InsertBlockS") ) {/code}

Simply open the Lisp file, scroll down and paste the code above. When AutoCad starts up now, this code will be loaded also. Change INSERTBLOCK to any name you wish. Test the command by typing INSERTBLOCk into the command bar. This should insert the block into modelspace.

To continue we have to hook this command to the F1 button.

Goto the ACAD.pgp file located in you Application data directory. Add the following code

S,        *INSERTBLOCK

This will connect the S key to the INSERTBLOCK routine. Type REINIT into the commandbar to reïnitialize the commandbar and then hit S to test the routine.

 

Login

Sign up now and upload your code to the website.

Help us to continue.....
Statistics
Articles View Hits
2330662
Latest Articles