Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

excel - How to go through a finite set of numbers in VBA?

In my workbook the worksheets equate to months; I was aiming to make a function that applied to the current month and the previous two (the last three months). But I run into trouble thinking of a way to get a 12 and 11 returned to me when January is the first month, or 01 and 12 for February, for example.

Function StockMedio(CodigoArtigo As String)

Dim mês As String
Dim ano As String
Dim LRow As Integer
Dim nome_folha As String

    mês = Format(Now(), "MM")
    ano = Format(Now(), "YY")
    LRow = Range("A3").End(xlDown).Row
    nome_folha = "Stock final " & mês & ano
   
        
End Function

So far I have this, I didn't type the code yet because it's not really relevant to the question. Any help? (Sorry for the code not being fully in english, it just makes it easier for me to understand it)

question from:https://stackoverflow.com/questions/65867140/how-to-go-through-a-finite-set-of-numbers-in-vba

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

But I run into trouble thinking of a way to get a 12 and 11 returned to me when January is the first month, or 01 and 12 for February, for example.

You can use DateAdd to get what you want. Here is an example

Option Explicit

Sub Sample()
    Dim dt As Date
    Dim PrevMonth As String
    Dim MonthPrevToPrevMonth As String
    
    dt = Now
    
    PrevMonth = Format(DateAdd("M", -1, dt), "M")
    MonthPrevToPrevMonth = Format(DateAdd("M", -2, dt), "M")
    
    Debug.Print PrevMonth
    Debug.Print MonthPrevToPrevMonth
End Sub

Here is a test with Jan and Feb dates.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...