2017-07-12 19 views
3

我在Today = Day(Today())上收到「expected array」錯誤。我不知道什麼是錯的。ROUNDUP當前日期爲15日或月末

Dim Thisday As Integer 
Dim Montho As Integer 
Dim Yearo As Integer 
Dim Lday As Integer 
Dim last as Integer 
last = Cells(Rows.Count, "A").End(xlUp).Row 
Thisday = Day(date) 
Montho = Month(date) 
Yearo = Year(date) 
Lday = Day(Application.WorksheetFunction.EoMonth(Date, -1)) 

然後在excel中的列B會被填入相同的日期,無論是第15天還是最後一天。

If Thisday <= 15 Then 
Range("B2:B" & Last).Value = Montho & "/15/" & Yearo 
End If 
If Thisday > 15 Then 
Range("B2:B" & Last).Value = Montho & "/" & Lday & "/" & Yearo 
End If 
End Sub 

也不是每個月都在30日結束,那麼Lday應該如何返回月份的日期。

+0

還是想出了相同的錯誤消息。 –

+0

對不起 - 我的錯誤:斯科特有它 –

回答

3

使用Date而不是Today

不要使用與函數相同的名稱,excel會搞砸。

vba沒有EoMonth它是Application.WorksheetFunction的一部分。它也返回一個日期或者double而不是一個整數。您將需要獲得Day

Dim Today As Integer 
Dim Montho As Integer 
Dim Yearo As Integer 
Dim Lday As Integer 
Dim last As Integer 
last = Cells(Rows.Count, "A").End(xlUp).Row 
Today = Day(Date) 
Montho = Month(Date) 
Yearo = Year(Date) 
Lday = Day(Application.WorksheetFunction.EoMonth(Date, 0)) 


If Today <= 15 Then 
    Range("B2:B" & Last).Value = Montho & "/15/" & Yearo 
End If 
If Today > 15 Then 
    Range("B2:B" & Last).Value = Montho & "/" & Lday & "/" & Yearo 
End If 

上面的代碼返回一個字符串,看起來像一個日期。返回一個真正的日期使用此:

Dim Today As Integer 
Dim Montho As Integer 
Dim Yearo As Integer 
Dim last As Integer 
last = Cells(Rows.Count, "A").End(xlUp).Row 
Today = Day(Date) 
Montho = Month(Date) 
Yearo = Year(Date) 


Range("B2:B" & Last).NumberFormat = "mm/dd/yyyy" 
If Today <= 15 Then 
    Range("B2:B" & Last).Value = DateSerial(Yearo, Montho, 15)  
End If 
If Today > 15 Then 
    Range("B2:B" & 4).Value = Application.WorksheetFunction.EoMonth(Date, 0) 
End If 
+0

仍然想出了相同的錯誤信息,但謝謝你糾正部分。 –

+0

然後,錯誤不在您顯示的代碼中。我讓它工作沒有問題。 @PhilippeMa確保你沒有聲明一個變量'Date' –

+0

這就是我所有的代碼,我沒有設置爲Date的變量。但是,您的日期顯示爲藍色,而我的日期不顯示。 –

1

嘗試,

Range("B2:B" & Last).Value = dateserial(year(date), month(date)-(day(date)>15), 15 * abs(day(date)<=15)) 
相關問題