【问题标题】:VBA: Open Input Box, Insert Month/Year and Return Previous Month YearVBA:打开输入框,插入月/年并返回上个月年
【发布时间】:2020-08-13 14:38:16
【问题描述】:

我一直在尝试配置我的 VBA 代码。这应该很简单,但是因为我很难将所有代码放在一起。

我想做的是编写一个 VBA 代码,在其中执行代码并弹出一个输入框,从那里我将月份和年份放入框中,返回的是输入日期之前的月份年份.

例如,如果我在输入框中输入 7/2020,则返回值为 6/2020。

到目前为止我的代码如下:

 Sub insertDateColumn()

 Dim myValue As Variant

 Worksheets("Sheet2").Columns("G:G").Insert

 myValue = InputBox("Month Year")

上面的代码将插入一列并打开一个输入框。从那里我不完全确定如何包含我将从输入框中获取值并减去一个月的代码。到目前为止,我已经想出了一个代码,它将使用 DateSerial 函数输入上个月和上一年。

 Sheet2.Range("G2") = DateSerial(Year(Date), Month(Date) - 1, 0)

`

任何建议、帮助或参考将不胜感激!

谢谢

【问题讨论】:

    标签: vba function


    【解决方案1】:

    你可以使用Split函数来完成你所需要的:

    Private Sub CommandButton1_Click()
       Dim myValue As String
       Dim myDate As Variant
    
       myValue = InputBox("Month Year")
       myDate = Split(myValue, "/")                            'break apart user input
       myDate = DateSerial(Val(myDate(1)), Val(myDate(0)), 1)  'make it into a real date
       myDate = DateAdd("m", -1, myDate)                       'subtract a month, allowing for rolling to previous year
       myDate = Month(myDate) & "/" & Year(myDate)             'rebuild in correct format
    
       Sheet2.Range("G2") = myDate
       Sheet2.Range("G3") = myDate
    End Sub
    

    当然,明智的做法是验证用户输入并增强代码以处理可能遇到的任何错误。

    【讨论】:

    • 这太棒了!感谢您提及拆分功能!如果我想将此数据放在 2 个单独的单元格中,我是否需要在 myDate 变量下定义我想要的单元格?
    【解决方案2】:
    Dim myValue As String
    myValue = InputBox("Month Year")
     
    Dim Mth, Yr As Integer
    Dim a, b, Result As String
    
    a = Left(myValue, 2)
    b = Right(myValue, 4)
    
        If a = "01" Then
             Yr = CInt(b) - 1
             Result = "12" & "/" & Yr
        Else
              Mth = CInt(a) - 1
              Result = Mth & "/" & b
        End If
    MsgBox Result
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-08
      • 2016-03-11
      • 2016-04-05
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      相关资源
      最近更新 更多