我有以下代碼:
Dim CurrMonth As Integer
Dim MonthPos As Variant
Dim CurrPos As Integer
CurrMonth = Month(Date) - 1
MonthPos = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
任何人都可以提供有關如何在給定索引 CurrMonth 的情況下從陣列 MonthPos 獲取(在這種情況下)字串元素的指導。
uj5u.com熱心網友回復:
請使用下一個適應的方式:
Sub extractMonth()
Dim CurrMonth As Long, MonthPos As Variant, CurrPos As Integer, prevMonth
CurrMonth = Month(Date) - 1
MonthPos = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
prevMonth = MonthPos(CurrMonth - 1) '- 1 because it is a zero based 1D array...
Debug.Print prevMonth 'the previous month (I could see Month(Date) - 1) and I supposed that this is needed.
'otherwise, you should simple use MonthPos(CurrMonth), for the current month
End Sub
uj5u.com熱心網友回復:
https://www.softwaretestinghelp.com/vba-array-tutorial/#One_Dimensional_Array提供以下示例:
Private Sub arrayExample3()
Dim thirdQuarter(13 To 15) As String 'creates array with index 13,14,15
thirdQuarter(13) = "July"
thirdQuarter(14) = "Aug"
thirdQuarter(15) = "Sep"
MsgBox "Third Quarter in calendar " & " " & thirdQuarter(13) & " " &
thirdQuarter(14) & " " & thirdQuarter(15)
End Sub
所以對于你的情況應該是:
MonthPos(CurrMonth)
uj5u.com熱心網友回復:
除了陣列,您還可以使用
Format$(date,"MMMM")
或者如果你需要前一個月
Format$(DateSerial(Year(Date),Month(Date)-1,1),"MMMM")
以作業系統的語言獲取月份的名稱。
uj5u.com熱心網友回復:
假設 Excel(一次性評估月份名稱陣列),以下方法允許輸入任何增量或減量作為可選的第二個引數:
Function getMonth(currMonth As Long, Optional MonthOffset As Long = 0)
'a) build array of month names via evaluation (Excel)
Dim months(): months = [Text(Date(0,Column(A:L),1),"mmmm")]
'b) calculate wanted month
currMonth = (currMonth MonthOffset 12) Mod 12
If currMonth = 0 Then currMonth = 12
'c) return month name
getMonth = months(currMonth)
End Function
示例呼叫
只需將可能的減量作為第二個引數傳遞:
Debug.Print getMonth(1) ' ~~> returns January
Debug.Print getMonth(1,-1) ' ~~> returns December
'assuming call as of 5/31 2022, i.e. equalling getMonth(5)
Debug.Print getMonth(Month(Date)) ' ~~> returns May
Debug.Print getMonth(Month(Date),-1) ' ~~> returns April
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483804.html
上一篇:如何編輯JSON陣列?
