【问题标题】:copy row range vba and title row based on criteria根据条件复制行范围 vba 和标题行
【发布时间】:2018-07-19 14:14:41
【问题描述】:

我尝试修改以下 VBA 编码。我只想复制 A:G 列和标题,而不是整行。你能帮我修改一下吗?此代码将根据 D 列中的条件将整行复制到标题为该条件的新工作表中。

Sub Load_data()
    Application.ScreenUpdating = False

    Dim lr As Long
    Dim ws As Worksheet
    Dim vcol, i As Integer
    Dim icol As Long
    Dim myarr As Variant
    Dim title As String  
    Dim titlerow As Integer

    vcol = 4
    Set ws = Sheets("Transaction Details")
    lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
    title = "A7:G7"
    titlerow = ws.Range(title).Cells(7).Row
    icol = ws.Columns.Count
    ws.Cells(1, icol) = "Unique"

    For i = 2 To lr
        On Error Resume Next

        If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
            ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
        End If
    Next

    myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol.SpecialCells(xlCellTypeConstants))
    ws.Columns(icol).Clear

    For i = 2 To UBound(myarr)
        ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""

        If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
            Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
        Else
            Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
        End If

        ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("B7")
        Sheets(myarr(i) & "").Columns.AutoFit
    Next

    ws.AutoFilterMode = False
    ws.Activate
End Sub

【问题讨论】:

  • 请注意Dim vcol, i As Integer 只声明i As Integervcol As Variant。您需要为 每个 变量指定一个类型:Dim vcol As Integer, i As Integer。 • 同样使用On Error Resume Next 而不进行错误处理也是一个坏主意。它只是在您的代码中隐藏 所有 错误消息,直到 End Sub,但错误仍然存​​在。你只是看不到它们。因此,您无法找到并修复该行下方的任何错误。删除它或实施完整的错误处理。

标签: vba excel criteria


【解决方案1】:

试试这个

ws.Range("A" & titlerow & ":G" & lr).Copy

【讨论】:

  • 完美运行!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多