CodexBloom - Programming Q&A Platform

How to avoid 'Type Mismatch' scenarios when using ArrayList in VBA with multiple data types?

👀 Views: 93 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
vba arraylist excel

I'm converting an old project and I tried several approaches but none seem to work. I'm working with a 'Type Mismatch' behavior when trying to add different types of data (strings, numbers, and dates) to an `ArrayList` in VBA. I am using Excel 2016 and have a requirement to store mixed data types in the same list for easier manipulation later. I initialized the `ArrayList` like this: ```vba Dim myList As Object Set myList = CreateObject("System.Collections.ArrayList") ``` After adding a few elements like this: ```vba myList.Add "Sample String" myList.Add 12345 myList.Add Date ``` I run the code and sometimes it works without issues, but occasionally when I attempt to retrieve the last element using: ```vba Dim lastElement As Variant lastElement = myList(myList.Count - 1) ``` I receive a runtime behavior: "Type Mismatch". I've read that `ArrayList` should handle multiple types, but I suspect something in my handling or retrieval of elements is causing this inconsistency. I've also tried using `Variant` as the variable type for `lastElement`, but that doesn't seem to resolve the scenario. Could anyone guide to understand why this happens and how I can consistently store and retrieve mixed data types without working with errors? I'm working on a API that needs to handle this. What's the correct way to implement this?