Duplicate declaration

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,924
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
Why is it this does not compile?


It is as if it ignores the If condition and declares b regardless, so you cannot declare it "twice".


Code:
Dim a As Long


If a = 10 Then


    Dim b As String


Else


    Dim b As Long
        
End If


Thanks
 
A dimension statement is not executable, it's a compiler directive. That's why you can't set a breakpoint on one.

You can use conditional compilation (#If/#Else) to declare variables, but the condition expression must be evaluable at compile time.
 
Last edited:
Upvote 0

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.
E..g.,

Code:
  [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=Const]#Const[/URL]  a = 10
  
  [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=If]#If[/URL]  a = 10 Then
    Dim b           As String
  [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=Else]#Else[/URL] 
    Dim b           As Long
  [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=End]#End[/URL]  If

  Debug.Print TypeName(b)
 
Upvote 0
@tiredofit

Alternatively, you could take advantage of the Variant type at runtime as follows :
Code:
Sub Test()

    Dim b As Variant
    Dim a As Long
    
    a = 10
    
    If a = 10 Then
        b = CStr(b)
    Else
        b = CLng(b)
    End If
    
    MsgBox TypeName(b)
    
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,893
Messages
6,175,240
Members
452,621
Latest member
Laura_PinksBTHFT

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top