I am new to VBA and trying to write a simple macro. I have pasted my code below. Basically, I have 11 random numbers in cells B5 through B15. If this number is less than 0.65 I would like it to print TRUE in the column next to it. If it is greater than 0.65 I would like it to print FALSE in the column next to it. I think I basically have the code down, however a “Next t” in the Sub PrintandRead, t will have a value 5 through 15 (which is correct) however then it goes up to the markov function where t then returns to t=0. Why is it not carrying the “Next t” value up into the function?
Option Explicit
Function markov(pwd As Double, pww As Double) As Boolean
Static wetYesterday As Boolean
pwd = 0.4
pww = 0.65
Dim c As Double
Dim t As Double
If wetYesterday Then c = t - pww Else c = t - pwd
If c <= 0 Then
wetYesterday = True: markov = True
Else
wetYesterday = False: markov = False
End If
End Function
Sub ReadAndPrint()
Dim t As Double
Dim p As Double
Dim z(11) As Double
Application.ScreenUpdating = False
Worksheets("Sheet1").Activate
p = 2
For t = 5 To 15
z(t - 4) = Cells(t, p)
Next t
p = p + 1
For t = 5 To 15
Cells(t, p) = markov(0.4, 0.65)
'z(t - 4)
Next t
End Sub
While you have a variable called
tin yourmarkovfunction, this is a different variable to the one in the mainReadAndPrintmethod. This is called scope – as you declare each variable within each method, it is scoped to that method. You can use the same name again elsewhere, but its a completely different variable (and could have a different type etc).The best thing you could do would be to pass
tinto themarkovmethod as a parameter by changing the declaration:and calling it with
You should also delete the
Dim t As Doublefrom themarkovfunction.