A compilation error caused by duplicate ads in the current area.
In other words: this means that you are declaring more than one variable with the same name.
Adding an Option Explicit statement on top of your modules requires declaring each variable that you use. This is very useful when getting this error, because you can quickly scan your code to re-declare the highlighted line Dim <variable_name>
This is an example demonstrating why you are getting the error:
Option Explicit Sub Main() Dim c As Worksheet For Each c In Sheets Dim c As Long ' you are going to get an error in here because ' a variable named: c, is already declared within the sub ' you can't have two variables named: c. For c = 1 To ws.Range("A" & Rows.Count).End(xlUp).Row ' some code Next c Next End Sub
No problem with your problem. We could provide a better solution to your problem if you better explain what you are trying to achieve.
There is a workaround to achieve what you want, but I would not recommend doing it this way if you are not sure what you are actually doing;). The following code will create a new module in your current VBA project. Iterating over an array with animal names, it will write new lines in Module2 , so after executing your module two will

For this code to work, you must add links to Microsoft Visual Basic for Applications Extensibility 5.3". You can do that by selecting Tools >> Links` in the VBE window.
In addition, this requires Trust Access to VBA Project Object Model . Go to Excel Settings โ Trust Center โ Macros โ check "Trust access to the VBA project object model."

Run the sample code.
Option Explicit ' this VBA project requires ' 1 - references to Microsoft Visual Basic For Applications Extensibility 5.3 ' add it via Tools > References ' ' 2 - trust access to VBA project object model ' In spreadsheet view go to Excel(application options) >> Trust Centre >> Macro Settings ' tick the Trust Access to VBA project object model Sub mymacro() Dim names names = Array("cat_code", "dog_code", "eagle_code") Dim c As Variant AddAModule For Each c In names ' dynamically create arrays WriteToModule CStr(c) Next CloseModule End Sub Private Sub AddAModule() Dim VBProj As VBIDE.VBProject Dim VBComp As VBIDE.vbComponent Dim CodeMod As VBIDE.CodeModule Set VBProj = ThisWorkbook.VBProject Set VBComp = VBProj.VBComponents.Add(vbext_ct_StdModule) Set CodeMod = VBComp.CodeModule With CodeMod .DeleteLines 1, .CountOfLines .InsertLines 1, "Public Sub DynamicallyCreatedArrays()" .InsertLines 2, " ' code for the sub" End With End Sub Private Sub WriteToModule(arrayName As String) With ActiveWorkbook.VBProject.VBComponents("Module2").CodeModule .InsertLines .CountOfLines + 2, " Dim " & arrayName & " as Variant" End With End Sub Private Sub CloseModule() With ActiveWorkbook.VBProject.VBComponents("Module2").CodeModule .InsertLines .CountOfLines + 2, "End Sub" End With End Sub
user2140173
source share