简体   繁体   English

Excel VBA在年份函数上编译错误

[英]excel vba compile error on year function

I am writing a vba subroutine in excel vba that totals the quantity of lbs sold to customers for varying years and for some reason I am getting a compile error with the year function. 我在excel vba中编写了一个vba子例程,该子例程汇总了不同年份向客户出售的lbs数量,由于某种原因,我遇到了year函数的编译错误。 Could someone please explain why? 有人可以解释为什么吗? Here's my code: 这是我的代码:

Private Sub lbsPerCustPerYear_Click()

Dim i As Integer
Dim Cust As String
Dim Cust2 As String
Dim Total As Integer
Dim Output As Range
Dim Output2 As Range
Dim Year1 As Date

Total = 0
Year1 = Range("K6").Value
Cust = Range("C6").Value
Cust2 = Range("C7").Value
Set Output = Sheets("Sheet2").Cells(2, 2)
Set Output2 = Sheets("Sheet2").Cells(2, 3)

For i = 1 To 14750
Year1 = Range("K5").Offset(i, 0).Value
If IsDate(Sheets("Sheet1").Cells(i, 11)) Then
If Cust = Cust2 And Year(Sheets("Sheet1").Cells(i, 11)) = 2012 Then
Total = Range("Q5").Offset(i, 0).Value + Range("Q6").Offset(i, 0).Value
Cust = Range("C5").Offset(i, 0).Value
Cust2 = Range("C6").Offset(i, 0).Value
Output.Value = Cust
Output2.Value = Total

Else
Cust = Range("C5").Offset(i, 0).Value
Cust2 = Range("C6").Offset(i, 0).Value
Year1 = Range("K5").Offset(i, 0).Value
Set Output = Output.Offset(1, 0)
Set Output2 = Output2.Offset(1, 0)

End If

Else
Cust = Range("C5").Offset(i, 0).Value
Cust2 = Range("C6").Offset(i, 0).Value
Year1 = Range("K5").Offset(i, 0).Value
Set Output = Output.Offset(1, 0)
Set Output2 = Output2.Offset(1, 0)

End If
Next i



End Sub

The error is in the line: 错误在该行中:

If Cust = Cust2 And Year(Sheets("Sheet1").Cells(i, 11).Value) = 2012 Then

Thanks in advance! 提前致谢!

Does each cell in column 11 contain a valid date or year? 第11列中的每个单元格都包含有效的日期或年份吗?

You could check this first: 您可以先检查以下内容:

If isdate(Sheets("Sheet1").Cells(i, 11).Value) then

  If Cust = Cust2 And Year(Sheets("Sheet1").Cells(i, 11).Value) = 2012 Then

......

  end if

else

'handle invalid date

end if

Something else I've noticed is you've used Year as a variable name, change this to dtYear or something as this may conflict with the Year function in the object library. 我注意到的另一件事是您使用Year作为变量名,将其更改为dtYear或其他名称,因为这可能与对象库中的Year函数冲突。

Yes, what you have done is correct. 是的,您所做的是正确的。 Now you only need to check whether 现在您只需要检查

1) Sheets("Sheet1").Cells(i, 11).Value This particular cell is formatted as date. 1) Sheets("Sheet1").Cells(i, 11).Value此特定单元格的格式设置为日期。

2) Try using this instead Sheets("Sheet1").Cells(i, 11) . 2)尝试改用Sheets("Sheet1").Cells(i, 11)代替。 Remove .value from the statement. 从语句中删除.value。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM