Is it possible to execute code written in specific excel cells?
For example: In Range("A1")
I have text -> debug.print("Test")
. I need some way to execute this from VBA code.
Is it possible?
Is it possible to execute code written in specific excel cells?
For example: In Range("A1")
I have text -> debug.print("Test")
. I need some way to execute this from VBA code.
Is it possible?
First, use this answer to ensure programmatic access to the VBA model. Then, use this method that makes a string parser for a simple command located in a worksheet cell. This should be enough to get you going.
Demo:
Option Explicit
Sub test()
Dim strCode As String
strCode = Sheet1.Range("A1").Text
StringExecute strCode
End Sub
Sub StringExecute(s As String)
' Credits to A.S.H., see https://stackoverflow.com/questions/43216390/how-to-run-a-string-as-a-command-in-vba
Dim vbComp As Object
Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
vbComp.CodeModule.AddFromString "Sub foo()" & vbCrLf & s & vbCrLf & "End Sub"
Application.Run vbComp.Name & ".foo"
ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub
No. You can't store code in the worksheet. But you can store the name of a procedure in a worksheet cell and then call that procedure using Application.Run
Short answer: No
You can only run code that is within the VBA editor. Therefore it is not possible to run code from a cell directly.
But …
But what you can do (as a workaround) is writing a procedure that extracts the VBA code from that cell and includes it into a module and then runs that code.
However even if this is possible this would be a task for a pro-user and it is not recommended for beginners (you should know what you do here).
Nevertheless if you want to have a look into how to add procedures/functions into the VBA Editor have a look at Programming The VBA Editor.
The closest you can easily get to your goal is to use VBA User Defined Functions. These can be called from worksheet formulas in the same way as native Excel functions.
But they have limitations compared to a VBA subroutine - the main one being that they can only return information to the cells that they occupy.