![](/img/trans.png)
[英]VBA code to copy cells in specific column and paste (value) it to cells in specific column on another Sheet based on conditions
[英]Vba code to compare columns that have cells containing dates and paste specific text to another column
我有點迷茫。我試圖創建一個宏,該宏將比較AH列的單元格與AH列的單元格(兩個列都包含DATES),並根據結果將文本打印到AI欄。 代碼在下面..每次我運行它時,都會顯示錯誤13類型不匹配,並突出顯示“ FirstDate = Cells(RowNumber,33)”行。 你能幫我解決這個問題嗎..
Sub Dates()
Sheets("1").Select
Dim Result As Long, RowNumber As Long
Dim FirstDate As Date, SecondDate As Date
RowNumber = 2
Do Until Cells(RowNumber, 2) = ""
FirstDate = Cells(RowNumber, 33)
SecondDate = Cells(RowNumber, 34)
Result = DateDiff("n", FirstDate, SecondDate)
If Result <= 30 Then
Cells(RowNumber, 35) = "On Time"
ElseIf Result > 30 Then
Cells(RowNumber, 35) = "Late"
End If
RowNumber = RowNumber + 1
Loop
End Sub
Sub Dates()
Dim Result As Long, RowNumber As Long
Dim FirstDate As Variant, SecondDate As Variant
Sheets("1").Select
RowNumber = 2
Do Until Cells(RowNumber, 2) = ""
FirstDate = Cells(RowNumber, 33).Value
SecondDate = Cells(RowNumber, 34).Value
If IsDate(FirstDate) Then
Result = DateDiff("n", FirstDate, SecondDate)
If Result <= 30 Then
Cells(RowNumber, 35) = "On Time"
ElseIf Result > 30 Then
Cells(RowNumber, 35) = "Late"
End If
Else
Cells(RowNumber, 35) = "Not A Valid Date"
End If
RowNumber = RowNumber + 1
Loop
End Sub
可能的原因是Cells(RowNumber,33)中的值不是日期。 Excel將日期存儲為數字。 將數字格式更改為“常規”。 如果您在單元格中看到一個數字,則為日期。 如果看到文字,則為文字。 如果文本看起來像日期,Excel可能會將其強制為正確的日期(表示數字)。 嘗試FirstDate = Cdate(Cells(RowNumber, 33).Value)
。
如果將單元格的“數字格式”設置為“ Date
,則可以輸入短日期(在“區域設置”中定義),Excel會將其記錄為實際日期(即數字)。 最好將日期記錄為“實際”日期,而不是您可以將其讀取為日期。
違反直覺? 那是Excel。 :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.