我是VBA的新手并尝试编写一个简单的宏。我在下面粘贴了我的代码。基本上,我在单元格B5到B15中有11个随机数。如果此数字小于0.65,我希望它在旁边的列中打印为TRUE。如果它大于0.65我希望它在它旁边的列中打印FALSE。我认为我基本上已经将代码关闭,但是Sub PrintandRead中的“Next t”,t将具有值5到15(这是正确的)然而它上升到markov函数,其中t然后返回到t = 0 。为什么它没有将“Next t”值带到函数中?
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
答案 0 :(得分:1)
虽然您的t
函数中有一个名为markov
的变量,但这与主ReadAndPrint
方法中的变量不同。这称为范围 - 当您在每个方法中声明每个变量时,它的范围限定为该方法。您可以在其他地方再次使用相同的名称,但它是一个完全不同的变量(并且可能有不同的类型等)。
您可以做的最好的事情是通过更改声明将t
作为参数传递给markov
方法:
Function markov(pwd As Double, pww As Double,t as Double) As Boolean
并用
调用它Cells(t, p) = markov(0.4, 0.65, z(t - 4))
您还应该从Dim t As Double
功能中删除markov
。
答案 1 :(得分:0)
您有两种选择:
在C列中执行以下操作:=IF(B5 > 0.65, "TRUE", "FALSE")
代码:
Option Explicit
Sub checkGreatness()
Dim inputRng As Range
Dim arrInput As Variant
Dim i As Integer
'--get user input
Set inputRng = Application.InputBox("Please enter Column Range", "Enter the Range", , , , , , 8)
If inputRng Is Nothing Then
Exit Sub
End If
'--populate array with that range
arrInput = WorksheetFunction.Transpose(inputRng.Value)
For i = LBound(arrInput) To UBound(arrInput)
If IsEmpty(arrInput(i)) Then
arrInput(i) = "NoValue"
ElseIf Round(arrInput(i), 2) < 0.65 Then
arrInput(i) = "True"
Else
arrInput(i) = "False"
End If
Next i
'--output to next column
inputRng.Offset(0, 1).Resize(UBound(arrInput), 1) = Application.Transpose(arrInput)
End Sub
输出: