【问题标题】:Trying to get two dates, 24th of last month and 23rd of this month试图获得两个日期,上个月的 24 日和本月的 23 日
【发布时间】:2018-08-09 12:53:34
【问题描述】:

我正在尝试获取两个日期作为变体,以便可以将它们换入和换出每个月运行的 SQL 查询(具有不同的时期)。我试图以"yyyy-mm-dd" 格式获取上个月的 24 日,以"yyyy-mm-dd" 格式获取本月的 23 日(程序运行时)。我有这段代码,但它给了我“错误数量的参数”作为错误,我不明白为什么。

Option Explicit
Sub mDateSet()
Dim fromDateFinal As String
Dim toDate As String
Dim toDateFinal As String
Dim fromDate: fromDate = Format(DateAdd("M", -1, Now), "yyyy-mmmm")
'Format gives 'wrong number of arguments or invalid property assignment error'

'trying to define two dates: the 24th of last month until the 23rd of this month)

    '24th of last month
    fromDateFinal = fromDate & "24"

            Debug.Print fromDateFinal

    '23th of this month
    toDate = Format(Date, "yyyy-mm")
    toDateFinal = toDate & "23"

            Debug.Print toDateFinal

End Sub

【问题讨论】:

  • 如果我运行这段代码,它会打印出2018-Februar242018-0323。因此,您应该添加 2 个破折号以获得良好的日期格式,但它在此处运行时没有任何错误。无法重现它。您确定问题中的代码正是您尝试过的代码吗?
  • 问题是@Axel Richter 说Format 是在项目中定义的,这就是我收到错误的原因。否则代码会(有点)功能,这就是为什么我不明白为什么它会给我一个错误。

标签: vba excel date


【解决方案1】:

这里有一些来自操纵日期和格式掩码的字符串日期。

fromDateFinal = format(date-day(date), "yyyy-mm-24")  '2018-02-24
toDateFinal = format(date, "yyyy-mm-23")              '2018-03-23

【讨论】:

  • 谢谢,这个看起来比我的代码简单多了。我们在另一个模块中定义了格式,所以把事情搞混了。
【解决方案2】:

如果 Format(DateAdd("M", -1, Now), "yyyy-mmmm") 产生该错误 (wrong number of arguments or invalid property assignment error) 并选择了 Format,那么在 <Global> 的某处定义了另一个函数 Format,它有更少或更多的参数。

试试VBA.Strings.Format(DateAdd("M", -1, Now), "yyyy-mmmm")

Strings.Format 是所需Format 函数的完全限定名称。

如果它确实选择了DateAdd,那么可能与此相同。那里的完全限定名称是VBA.DateTime.DateAdd

【讨论】:

  • 谢谢您,问题正是您所说的。多个人正在处理控制 SQL 查询的同一个宏,我想我从来没有想过定义 Format 是问题。
  • @Rhyfelwr:如果是我,我会解雇在<Global> 中将Format 定义为SubFunction 名称的人。至少冲着他的脸尖叫;-)。
  • @AxelRichter 这正是您只想静静地站起来,在一天剩下的时间里走出门的时刻,因为您有心情杀死任何进入您房间的人。
  • 斗争是真实的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多