Does anybody here know how to get VBA to run multiple threads? I am using Excel.
VBA is built in a single-threaded apartment. The only way to get multiple threads is to build a DLL in something other than VBA that has a COM interface and call it from VBA.
To enable the multi-threading feature, click the FILE tab and select Options to open the Excel Options dialog box, as mentioned earlier. Click Advanced in the menu on the left. Scroll down to the Formulas section and select the Enable multi-threaded calculation check box so there is a check mark in the box.
What is MultiThreading? Multithreading enables us to run multiple threads concurrently. For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed. So multithreading improves the responsiveness of a system.
Multithreading is the ability of a program or an operating system to enable more than one user at a time without requiring multiple copies of the program running on the computer. Multithreading can also handle multiple requests from the same user.
Can't be done natively with VBA. VBA is built in a single-threaded apartment. The only way to get multiple threads is to build a DLL in something other than VBA that has a COM interface and call it from VBA.
INFO: Descriptions and Workings of OLE Threading Models
As you probably learned VBA does not natively support multithreading but. There are 3 methods to achieve multithreading:
I compared all thread approaches here: http://analystcave.com/excel-multithreading-vba-vs-vbscript-vs-c-net/
Considering approach #3 I also made a VBA Multithreading Tool that allows you to easily add multithreading to VBA: http://analystcave.com/excel-vba-multithreading-tool/
See the examples below:
Multithreading a For Loop
Sub RunForVBA(workbookName As String, seqFrom As Long, seqTo As Long) For i = seqFrom To seqTo x = seqFrom / seqTo Next i End Sub Sub RunForVBAMultiThread() Dim parallelClass As Parallel Set parallelClass = New Parallel parallelClass.SetThreads 4 Call parallelClass.ParallelFor("RunForVBA", 1, 1000) End Sub
Run an Excel macro asynchronously
Sub RunAsyncVBA(workbookName As String, seqFrom As Long, seqTo As Long) For i = seqFrom To seqTo x = seqFrom / seqTo Next i End Sub Sub RunForVBAAndWait() Dim parallelClass As Parallel Set parallelClass = New Parallel Call parallelClass.ParallelAsyncInvoke("RunAsyncVBA", ActiveWorkbook.Name, 1, 1000) 'Do other operations here '.... parallelClass.AsyncThreadJoin End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With