试图解决这个问题。
我有此示例数据来获取介于Date From和Date to之间的行:
Sheet1
此工作表包含“日期自:”和“日期至:”单元格,这些单元格将自动在下面显示结果
这是我的Sheet2提取的数据
这是我当前的VBA代码。
Sub FinalData()
Dim lastrow As Long
Dim count As Integer
Dim p As Integer
Dim x As Integer
lastrow = Sheets("Sheet2").Cells(rows.count, 1).End(xlUp).row
Sheets("Sheet1").Range("A5:C1000").ClearContents
count = 0
p = 5
For x = 2 To lastrow
If Sheets("Sheet2").Range("C2:C100") >= Sheets("Sheet1").Cells(1, 2) AND Sheets("Sheet2").Range("C2:C100") <= Sheets("Sheet1").Cells(2, 2) Then
Sheets("Sheet1").Cells(p, 1) = Sheets("Sheet2").Cells(x, 1)
Sheets("Sheet1").Cells(p, 2) = Sheets("Sheet2").Cells(x, 2)
Sheets("Sheet1").Cells(p, 3) = Sheets("Sheet2").Cells(x, 3)
p = p + 1
count = count + 1
End If
Next x
MsgBox " The number of data found for this Area is " & " " & count
End Sub
我的代码有问题吗?这段代码在我的上一个项目中工作正常,但是当我尝试使用它来获取Date的行时。我认为问题出在我提出的条件声明上。
答案 0 :(得分:1)
问题是您正在尝试将一个单元格范围与两个单元格进行比较。
未经测试:
Sub FinalData()
Dim lastrow As Long
Dim count As Long
Dim p As Long
Dim x As Long, dt
Dim wsReport As Worksheet, wsData As Worksheet
Set wsReport = ThisWorkbook.Sheets("Sheet1")
Set wsData = ThisWorkbook.Sheets("Sheet2")
lastrow = wsData.Cells(Rows.count, 1).End(xlUp).Row
wsReport.Range("A5:C1000").ClearContents
count = 0
p = 5
For x = 2 To lastrow
dt = wsData.Cells(x, "C")
If dt >= wsReport.Cells(1, 2) And dt <= wsReport.Cells(2, 2) Then
With wsReport
.Cells(p, 1) = wsData.Cells(x, 1)
.Cells(p, 2) = wsData.Cells(x, 2)
.Cells(p, 3) = wsData.Cells(x, 3)
End With
p = p + 1
count = count + 1
End If
Next x
MsgBox " The number of data found for this Area is " & " " & count
End Sub