Methods_DoLoop
Methods_DoLoop
Do-loop
1
REVISION
Option Explicit
Sub Testing_Sub()
Debug.print Testing_Calc
Sub DoUntilDemo()
End Sub Do Until IsEmpty(ActiveCell.value)
ActiveCell.value = ActiveCell.value * 2
Function Testing_Calc() As Integer ActiveCell.offset(1, 0).Select
Testing_Calc = 10 Loop
End Function End Sub
• Rules
• If the value of a variable is NOT going to be changed within a method, use ByVal
• If the value of a variable is going to be changed within a method but the value makes NO
IMPACT to the caller method, use ByVal
• If the value of a variable is going to be changed within a method and the value makes
IMPACT to the caller method, use ByRef 2
File:
Methods StockTable.xlsm
Expected to learn:
Sub and Function
• Description: ByRef and ByVal
• Create a macro that utilizes methods for its Do-loop
IsEmpty()
implementation. This macro program is designed Range(col & "1")
to compute the Simple Moving Average (SMA) of
n data points, where n represents any positive ChatGPT
value.
• Utilize ChatGPT to professionally revise the
program.
SMA
Sub CalcSMA_5()
Dim count As Integer
Dim row As Long
Dim sum As Double
Sub CalcSMA_5() Sub CalcSMA_10()
Range("H1").Value = "SMA-5"
row = 2
Dim count As Integer Dim count As Integer
count = 1 Dim row As Long Dim row As Long
sum = 0 Dim sum As Double Dim sum As Double
'Check if Adj close value exists or not Range("H1").Value = "SMA-5" Range("I1").Value = "SMA-10"
Do Until IsEmpty(Cells(row, 7)) row = 2 row = 2
count = 1 count = 1
' accumulate values for calculating SMA-5 sum = 0 sum = 0
sum = sum + Cells(row, 7)
Do Until IsEmpty(Cells(row, 7)) Do Until IsEmpty(Cells(row, 7))
' Check if all 5 data are stored or not
sum = sum + Cells(row, 7) sum = sum + Cells(row, 7)
If count >= 5 Then
If count >= 5 Then If count >= 10 Then
' Write the result to column H Cells(row - 4, "H") = sum / 5 Cells(row - 9, "I") = sum / 10
Cells(row - 4, "H") = sum / 5 sum = sum - Cells(row - 4, 7) sum = sum - Cells(row - 9, 7)
End If End If
' Subtract the first value from the Sum row = row + 1 row = row + 1
sum = sum - Cells(row - 4, 7) count = count + 1 count = count + 1
Loop Loop
End If End Sub End Sub
' Update the row and count values
row = row + 1
count = count + 1
Loop
End Sub
SMA
Sub CalcSMA_5() Sub CalcSMA_10()
Dim count As Integer Dim count As Integer
Dim row As Long Dim row As Long
Dim sum As Double Dim sum As Double