[英]Loop in elements of Array dynamically based on logic using VBA
我正在編寫一段代碼來使用 VBA 中的 Arrays 概念來選擇當前和下一季度的值。 但是,我在運行以下代碼時面臨運行時錯誤 13。
Sub PlaceTheQuarter()
Dim arr, Q1, Q2, Q3, Q4
arr = Array(1, "Q1", 2, "Q2", 3, "Q3", 4, "Q4")
Q1 = Array("Jan", "Feb", "Mar")
Q2 = Array("Apr", "May", "Jun")
Q3 = Array("Jul", "Aug", "Sep")
Q4 = Array("Oct", "Nov", "Dec")
'MsgBox (Application.Match(Application.RoundUp(Month(Date) / 3, 0)))
MsgBox (arr(Application.Match(Application.RoundUp(Month(Date) / 3, 0), arr, 0)))
'ENABLE THIS PART TO TEST Q4 ITERATION
Dim idate As Date
idate = "31-DEC-2020"
a = arr(Application.Match(Application.RoundUp(Month(idate) / 3, 0), arr, 0))
'a = arr(Application.Match(Application.RoundUp(Month(Date) / 3, 0), arr, 0))
i = Mid(a, 2, 1)
Dim next_q As Integer
If i = 4 Then
next_q = 1
Else
next_q = i + 1
End If
MsgBox ("Next Quarter is: Q" & next_q)
MsgBox (MonthName(Month(idate), True))
counter = 0
Dim n_quarter
n_quarter = "Q" & next_q
For Each ab In Q4
If MonthName(Month(idate), True) = ab Then
MsgBox ab
Dim pos As Integer
pos = Application.Match(ab, Q4, False)
MsgBox pos
Else
End If
Next
End Sub
基本上在 Foreach 循環中,如果我手動使用季度名稱作為 Q4,它會很好地循環。但是我想根據Q&next_q
之類的值動態傳遞它。我已經分配了一個字符串值並在此處傳遞了該變量,這不是要么在我的情況下工作。
對此的任何指示都非常感謝......
我的意圖是讓相應的季度數組隨着一年中的日期進展而循環。
請測試下一個代碼。 它應該像(我理解的)你在上一條評論中要求的那樣:
Sub PlaceTheQuarter()
Dim arr, arrQ, Q1, Q2, Q3, Q4, ab, a As String, i As Long, k As Long
Dim next_q As Long, next_month As Long, arrFin, j As Long, actQ As Long
arr = Array(1, "Q1", 2, "Q2", 3, "Q3", 4, "Q4")
Q1 = Array("Jan", "Feb", "Mar")
Q2 = Array("Apr", "May", "Jun")
Q3 = Array("Jul", "Aug", "Sep")
Q4 = Array("Oct", "Nov", "Dec")
arrQ = Array(Q1, Q2, Q3, Q4)
Dim idate As Date: idate = Date '"02.10.2021"
a = arr(Application.match(Application.RoundUp(Month(idate) / 3, 0), arr, 0))
Select Case a
Case "Q1": next_month = Month(idate): actQ = 0
Case "Q2": next_month = Month(idate) - 3: actQ = 1
Case "Q3": next_month = Month(idate) - 6: actQ = 2
Case "Q4": next_month = Month(idate) - 9: actQ = 3
End Select
ReDim arrFin((3 - next_month) + 2)
i = Mid(a, 2, 1)
If i = 4 Then
next_q = 1
Else
next_q = i + 1
End If
'fill the final array containing the remained month plus the next quarter months:
For j = next_month To 2
arrFin(k) = arrQ(actQ)(j): k = k + 1
Next j
For j = 0 To 2
arrFin(k) = arrQ(next_q - 1)(j): k = k + 1
Next j
'______________________________________________________
'Iterate between the necessary array elements:
For Each ab In arrFin
Debug.Print ab
Next
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.