2015-06-15 53 views
0

我有一个非常简单的问题(但还没有我在它一直停留了一段时间)。有谁知道如何从DD/M/YYYY的日期值到DD/MM/YYYY的变量?日期格式 - 使DD/M/YYYY为DD/MM/YYYY

dim lastdaylastmonth as date 

lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0) 

所以这个代码,现在,将返回上个月的最后一天,所以它将是31/5/2015。对于格式的缘故,和MID()沿码拔出月份字符串“05”的时候,我将需要转换的日期,以DD/MM/YYYY或31/05/2015。有谁知道这个简单的解决方案?我试过了:

lastdaylastmonth = format(DateSerial(Year(Date), Month(Date), 0), "dd/mm/yyyy") 

它仍然返回相同的值!那里有英雄吗? :d

+1

谷歌是你再合适不过了! – Sorceri

回答

2

使用字符串

Sub dural() 
    Dim lastdaylastmonth As String 
    lastdaylastmonth = Format(DateSerial(Year(Date), Month(Date), 0), "dd/mm/yyyy") 
    MsgBox lastdaylastmonth 
End Sub 

enter image description here

+0

++是啊,这只是一个小的变化:)'Format'返回一个字符串 –

+0

@SiddharthRout并把它留在一个** **字符串变量有助于确保该变量将是“语法分析” –

0

看到这个:

lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0) 
?lastdaylastmonth 
31.05.2015 
? format(lastdaylastmonth,"dd.mm.yyyy") 
31.05.2015 
? format(lastdaylastmonth,"mm") 
05 

最后的输出是一个字符串,准备在你的代码中使用。

0

我喜欢这种方法只是由于这样的事实,我必须处理世界各地的许多不同版本的Excel。使用格式“MM/DD/YYYY”将只在美国工作(或徘徊无论英语是定义语言)。在其他国家代码下面的代码仍然可以工作。

Dim lastdaylastmonth As Date 

'Last day of last month 
lastdaylastmonth = Date - Day(Date) - 1 

'Formatting it US-style regardless of international Excel or Windows settings 
Debug.Print Right("0" & Day(lastdaylastmonth), 2) & "/" & Right("0" & Month(lastdaylastmonth), 2) & "/" & Year(lastdaylastmonth)