根据列值在Excel VBA中从一张工作表复制行到工作表

时间:2012-05-11 14:33:44

标签: excel-vba vba excel

Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim wks As Worksheet
On Error GoTo Err_Execute


For Each wks In Worksheets
    ThisWorkbook.Worksheets.Add After:=Worksheets(Worksheets.Count)
    Set wksCopyTo = ActiveSheet
    wks.Rows(3).EntireRow.Copy wksCopyTo.Rows(3)

    'Start search in row 4
    LSearchRow = 4
    'Start copying data to row 2 in Sheet2 (row counter variable)
    LCopyToRow = 4

    While Len(wks.Range("A" & CStr(LSearchRow)).Value) > 0
        'If value in column E = "Mail Box", copy entire row to Sheet2
        If wks.Range("AB" & CStr(LSearchRow)).Value = "Yes" And wks.Range("AK" & CStr(LSearchRow)).Value = "Yes" And wks.Range("BB" & CStr(LSearchRow)).Value = "Y" Then
            'Select row in Sheet1 to copy
            wks.Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
            Selection.Copy
            MsgBox "Copying Row"
            'Paste row into Sheet2 in next row
            wksCopyTo.Select
            wksCopyTo.Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
            wksCopyTo.Paste
            MsgBox "Pasting Row"
            'Move counter to next row
            LCopyToRow = LCopyToRow + 1
            'Go back to Sheet1 to continue searching
            wks.Select
        End If
        LSearchRow = LSearchRow + 1
    Wend

    'Position on cell A3
    Application.CutCopyMode = False
    Range("A3").Select
    MsgBox "All matching data has been copied."
Next wks

Exit Sub
Err_Execute:
    MsgBox "An error occurred."

你好

我有上面的代码,它基于其他地方给出的代码。在复制那些符合if语句中给出的条件的行时,代码已经过调整,我需要它来为每个现有工作表创建一个新的工作表。我遇到的问题是:

  1. excel是否允许您在运行代码之前首先找到所有工作表,这样您就不会在循环中循环?
  2. 我在处理一个工作表时给出的代码在一段时间后不会执行,我看不出原因?
  3. 当我在一个工作表上运行它时,它会在32,000行后崩溃
  4. 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我会逐一回答你的问题:

  1. 是。您可以使用ThisWorkbook.Worksheets.Count之类的内容来返回当前工作簿所具有的工作表数。然而,遍历工作表的最佳方法是通过Worksheets Collection:

    进行迭代
    Dim wks As Worksheet
    
    For Each wks In ThisWorkbook.Worksheets
        'Do something
        '...
    Next wks
    
    Set wks = Nothing
    
  2. 您永远不会退出循环(如果您在A列中有> 32,000行数据),直到您遇到溢出错误(整数只能达到32,767 +/-)。

  3. 参见第2点。您正在循环超出整数的限制。将数据类型更改为Long和/或如第2点所述,在某个时刻退出循环。