Press enter to see results or esc to cancel.

How to execute Apex anonymous code from Visual Studio Code

Hello folks,

In this short blog, We will see how to execute anonymous apex code in visual studio code. Once you are in the project folder and authenticated to your org ( you can see the present authenticated org for the project at the bottom left of the visual studio code with its Alias name).

  1. Please have the anonymous piece of code in scripts–>apex–>filename.apex  ( If the file is not present create one with .apex file type)
  2.  Once your anonymous piece of code is ready Click Ctrl+Shift+P to open command Pallete where you can see the command sfdx: Execute Anonymous Apex with editor contents.
  3. This will execute the below command in Output ( You need to open the terminal if not already). Please Observe there is a temporary file (tempApex.input) where the content of the .apex file will be carried and executed.

    sfdx force:apex:execute –apexcodefile c:\Users\sreddyk\Desktop\LWC\anonymousCode\.sfdx\tools\tempApex.input

  4. You can find the tempApex.input under .sfdx–> tools –> testresults –> tempApex.input
I understand your problem what if the .apex contains lots of anonymous piece of codes which you might be using for testing purpose. Well, hold on this blog post not completed yet.
  1. In case your .apex file contains lots of anonymous piece of codes then select the piece of code you want to execute
  2. Click Ctrl+Shift+P to open command Pallete where you can see the command sfdx: Execute Anonymous Apex with Currently selected text. Visual Studio Code is already smart enough to show you with this command 😛
  3. In this case, tempApex.input will be populated/executed with only selected text from .apex file.
Watch the below video: