排序宏无法正常运行

时间:2016-07-21 14:41:34

标签: excel vba excel-vba

我已经编写了一个宏来剪切并将一行中的行(“新供应商 - FPPE”)粘贴到基于列(H)的多个工作表中。当我第一次使用它时,它运行良好,但是当我在分拣表(“新供应商 - FPPE”)中添加了额外的数据时,它没有完全正常运行。宏继续从“新提供者 - FPPE”中删除行,但行无法填充到工作表上。我不知道行的去向。有没有人对可能发生的事情有任何见解?我非常擅长编写宏,所以感谢任何帮助!

Option Explicit

Sub Fr33M4cro()

Dim sh33tName As String
Dim custNameColumn As String
Dim i As Long
Dim stRow As Long
Dim customer As String
Dim ws As Worksheet
Dim sheetExist As Boolean
Dim sh As Worksheet

sh33tName = "New Providers - FPPE"
custNameColumn = "H"
stRow = 7

Set sh = Sheets(sh33tName)

For i = sh.Range(custNameColumn & sh.Rows.Count).End(xlUp).Row To stRow Step -1
    customer = sh.Range(custNameColumn & i).Value
    For Each ws In ThisWorkbook.Sheets
        If StrComp(ws.Name, customer, vbTextCompare) = 0 Then
            sheetExist = True
            Exit For
        End If
    Next
    If sheetExist Then
        CopyRow i, sh, ws, custNameColumn
    Else
        InsertSheet customer
        Set ws = Sheets(Worksheets.Count)
        CopyRow i, sh, ws, custNameColumn
    End If
    Reset sheetExist
Next i

End Sub

Private Sub CopyRow(i As Long, ByRef sh As Worksheet, ByRef ws As Worksheet, custNameColumn As String)
Dim wsRow As Long
wsRow = ws.Range(custNameColumn & ws.Rows.Count).End(xlUp).Row + 1


ws.Rows(wsRow).EntireRow.Value = sh.Rows(i).EntireRow.Value
sh.Rows(i).EntireRow.Delete
End Sub


Private Sub Reset(ByRef x As Boolean)
x = False
End Sub

Private Sub InsertSheet(shName As String)
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = shName
End Sub

1 个答案:

答案 0 :(得分:0)

我建议您将InsertSheet子更改为返回对插入的工作表的引用的函数:

Function InsertSheet(shName As String) As Worksheet
    Set InsertSheet = Worksheets.Add(After:=Worksheets(Worksheets.Count))
    InsertSheet.Name = shName
End Function

然后更改代码的这一部分:

    InsertSheet customer
    Set ws = Sheets(Worksheets.Count)
    CopyRow i, sh, ws, custNameColumn

到此:

    Set ws = InsertSheet(customer)
    CopyRow i, sh, ws, custNameColumn