首页 > 解决方案 > 如何在日期之间将数据拉到新工作表并在单元格中搜索字符串/值,并且只打印具有指定字符串的行

问题描述

我目前正在尝试根据用户输入指定的日期范围将数据从一张纸拉到另一张纸上。我还想指定仅在单元格具有特定字符串值的情况下提取行。字符串值为 Hot、Warm 或 Cold。

TextBox1 takes the first date 

TextBox2 takes the second date 

单击按钮时,工作表然后从“原始数据”中获取数据并打印到工作表“选定数据”

这是表单的样子:

形式

这是数据的样子:

原始数据

例如:我如何提取 2019 年 1 月 1 日至 2019 年 12 月 31 日(用户输入的日期)之间只有热值为 Hot 的数据。

Private Sub CommandButton1_Click()

Dim lrow As Long, i As Long, x As Date, y As Date, erow As Long

x = TextBox1
y = TextBox2

With Sheets("Raw Data")
    lrow = .Range("A" & .Rows.Count).End(xlUp).Row
    For i = 2 To lrow
        If Cells(i, 1) * 1 >= x * 1 Then
            If Cells(i, 1) * 1 <= y * 1 Then
                With Sheets("Selected Data")
                    erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
                End With
                .Range(.Cells(i, 1), .Cells(i, 12)).Copy _
                    Destination:=Sheets("Selected Data").Cells(erow, 1)
            End If
        End If
    Next i
End With

End Sub

Private Sub UserForm_Initialize()
ComboBox1.List = Array("Hot", "Warm", "Cold", "#N/A")

End Sub

标签: excelvba

解决方案


试试看,这个宏将比较第一个日期和最后一个日期,然后检查它是否“热”:

 Private Sub CommandButton1_Click()

    Dim Compteur As Long
    Dim wS As Worksheet, LastRow As Long
    Set wS = ThisWorkbook.Worksheets("Raw Data")

    'Here we look in Column A
    LastRow = wS.Cells(wS.Rows.Count, "A").End(xlUp).Row
    'Debug.Print LastRow


  For Compteur = 2 To LastRow


    If CDate(Cells(Compteur, 1).Value) < CDate(textbox2) And CDate(Cells(Compteur, 1).Value) > CDate(textbox1) Then
        If Cells(Compteur, 12) = "Hot" Then
            Sheets("Selected Data").Rows(ActiveWorkbook.Worksheets("Selected Data").Cells(Rows.Count, 1).End(xlUp).Row + 1) = Sheets("Raw Data").Rows(Compteur).Value
        End If

    End If

  Next Compteur



End Sub

推荐阅读