如何从 Spin Buttons 获取年和月的数据到特定的单元格?

How to get years and months data from Spin Buttons to specific cells?

我创造了,

SpinButton1 SpinButton2 个月
TextBox1 来自 SpinButton1 和来自 SpinButton2

TextBox2

"E2" 来自 SpinButton1 和 "F2" 来自 SpinButton2.

当我将“E2”更改为 yyyy 格式时,它会将值从 2022 更改为 1905 "F2" 为 mmmmm 格式,它不会改变任何。

如何将“G2”创建为 yyyy-mmyyyy-mmm 格式?

Private Sub SpinButton1_Change()

SpinButton1.Max = 2030
SpinButton1.Min = 2021
SpinButton1.SmallChange = 1
TextBox1.Value = SpinButton1.Value

End Sub

Private Sub SpinButton2_Change()

Dim Mths As Variant
  SpinButton2.Max = 11
  SpinButton2.Min = 0
  Mths = Array("Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec")

  TextBox2.Text = Mths(SpinButton2.Value)

End Sub

Private Sub TextBox1_Change()

ActiveSheet.Range("E2") = SpinButton1.Value

End Sub

Private Sub TextBox2_Change()

ActiveSheet.Range("F2") = TextBox2.Text

End Sub

When I change the "E2" as yyyy format, it changes the value to 1905 from 2022

整数 值“1”传递给具有“短日期”格式的单元格,将 return 01.01.1900.就是这样,因为 Excel 将其解释为从约定的开始时间 01.01.1900 开始经过的天数。

在您的情况下,您传递的值是 2022,因此 Excel 计数:01.01.1900 + 2022 天 = 14.07.1905.

"F2" as mmm or mm format, it doesn't change any.

此处类似 - 您传递了一个 字符串 值,因此 Excel 不知道那是否应该是一年中的一个月。

解决方案是以“yyyy-mm-dd”格式构造日期,并将输出单元格的格式设置为类似日期的格式。

最后解决你的问题:

  1. 我会使用额外的程序来构建日期:

     Private Sub MakeDate(sp1Val as String, sp2Val As String)
     Dim tempDate As Date
    
     tempDate = DateValue(sp1Val & "-" & sp2Val + 1 & "-" & 1)
    
     With Range("G2")
         .NumberFormat = "yyyy-mmm"
         .Value = tempDate
     End With
    
     End Sub
    
  2. 然后在您的两个 SpinButtonX_Change() 触发器中调用此过程,如下所示:

     Private Sub SpinButton2_Change()
     Dim Mths As Variant
     SpinButton2.Max = 11
     SpinButton2.Min = 0
     Mths = Array("Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec")
    
     Call MakeDate(SpinButton1.Value, SpinButton2.Value)
    
     End Sub
    

请注意,您将 SpinButton2 的值作为 整数 而不是字符串传递。你从 0 开始 索引,所以你必须在构建日期时输入 sp2Val + 1 (正如我在代码中所做的那样)。

希望对你有所帮助:)