Type Mismatch Error

Juggler_IN

Active Member
Joined
Nov 19, 2014
Messages
358
Office Version
  1. 2003 or older
Platform
  1. Windows
Hi,

I am getting a Type Mismatch Error in the following code:

Code:
Sub z()

Dim u1 As Double, u2 As Double, m As Double, s As Double, i As Long
Dim z(1 To 2) As Double


m = 0
s = 1


For i = 1 To 100


u1 = Rnd()
u2 = Rnd()


z(1) = Sqr(-2 * Log(u2)) * Cos(2 * Application.WorksheetFunction.pi * u1)
z(2) = Sqr(-2 * Log(u2)) * Sin(2 * Application.WorksheetFunction.pi * u1)


Range("E" & i).Value = m + s * z


Next


End Sub

I am not able to identify the cause. Help appreciated.
 

Excel Facts

Repeat Last Command
Pressing F4 adds dollar signs when editing a formula. When not editing, F4 repeats last command.
Rich (BB code):
Sub z()

Dim u1 As Double, u2 As Double, m As Double, s As Double, i As Long
Dim z(1 To 2) As Double


m = 0
s = 1


For i = 1 To 100


u1 = Rnd()
u2 = Rnd()


z(1) = Sqr(-2 * Log(u2)) * Cos(2 * Application.WorksheetFunction.pi * u1)
z(2) = Sqr(-2 * Log(u2)) * Sin(2 * Application.WorksheetFunction.pi * u1)


Range("E" & i).Value = m + s * z


Next


End Sub

You're defining z as a 2-element array, and then at the bottom, you don't give a subscript to z. It should be z(1) or z(2).
 
Upvote 0
I don't have time to analyze that entire code, but if you look at the original code, RandNorm is not defined in a Dim statement, making it a variant. This variant happens to hold an array variable, which is passed back as the result of the RandNorm function. Then the calling function refers to the 2 elements of the array separately.

Since I don't entirely understand the original code, or what you're trying to do with it, I can't comment on that. I can just point out why VBA is griping at you.
 
Upvote 0

Forum statistics

Threads
1,224,820
Messages
6,181,154
Members
453,021
Latest member
Justyna P

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