【发布时间】:2018-08-08 01:13:05
【问题描述】:
我有一个 Excel 用户窗体,用户可以在其中输入开始和结束日期,并从 2 个组合框(ComboBox1 和 ComboBox2)中选择数据。以下代码搜索这些日期之间的行,其余代码(为简单起见未显示)将该行复制到新工作表。
For Each c In rng.Cells
If (c.value >= startDate And c.value <= endDate) Or _
(c.Offset(0, 2).value >= startDate And c.Offset(0, 2).value <= endDate)
我想将 ComboBox1.value 和 ComboBox2.value 添加到搜索条件中,如果其中任何一个 ComboBox 留空,则忽略搜索过滤器的该部分。任何帮助将不胜感激!
更新:
我在这里超级困惑,而且我对 VBA 还是很陌生。我似乎仍然无法弄清楚这一点,并希望在这里提供任何帮助。下面是我尝试破解的代码,但我什至不知道我是否走在正确的轨道上。
Dim rng As Range, destRow As Long
Dim shtSrc As Worksheet, shtDest As Worksheet
Dim c As Range '-- this is used to store the single cell in the For Each loop
Dim d As Range '-- this is used to store the single cell in the For Each loop
Set shtSrc = Sheets("Projects") ' Sets "Projects" sheet as source sheet
Set shtDest = Sheets("Look Ahead") 'Sets "Look Ahead" sheet as destination sheet
destRow = 5 'Start copying to this row on destination sheet
' >> Set range to search for dates in Look Ahead period <<
Set rng = Application.Intersect(shtSrc.Range("J:Q"), shtSrc.UsedRange)
' >> Look for matching dates in columns Q and S on Projects Sheet <<
For Each c In rng.Cells
If (c.value >= startDate And c.value <= endDate) Or _
(c.Offset(0, 2).value >= startDate And c.Offset(0, 2).value <= endDate) Then ' Does date fall between start and end dates? If Yes, then copy to destination sheet
End If
Next
For Each d In rng.Cells
If (d.value = ComboBox2) Or _
(d.Offset(0, 2).value = ComboBox2) Then
shtSrc.Range("C" & c.Row).Copy shtDest.Range("B" & destRow)
shtSrc.Range("G" & c.Row).Copy shtDest.Range("A" & destRow)
shtSrc.Range("J" & d.Row).Copy shtDest.Range("E" & destRow)
shtSrc.Range("Q" & c.Row).Copy shtDest.Range("C" & destRow)
shtSrc.Range("S" & c.Row).Copy shtDest.Range("D" & destRow)
destRow = destRow + 1
' > Ends search <
End If
Next
【问题讨论】: