将值从一个工作簿排序到另一个工作簿中的正确工作表

时间:2014-02-06 09:55:42

标签: excel vba

我有一个非常基本的问题。我有一个包含大量列出信息的大型工作簿。我想将一些信息写入新工作簿并在不同的工作表上进行排序。我在使代码了解哪个选项卡需要放入信息时遇到了一些问题。 strName = Range(单元格值)不起作用,我真的不知道我做错了什么。我怎样才能使这个工作?对于非常混乱的代码感到抱歉。

Private Sub CommandButton1_Click()

Dim strName As String

Set sourceWq = Workbooks("SD KPIs 2014 onwards").Worksheets("VQN+Concessionn")
Set front = Workbooks("databank progging").Worksheets("Frontpage")

 For l = 5 To 30
    For i = 2 To 250000 'Goes through the sourceWq workbook
    If front.Cells(l, 13).Value = sourceWq.Cells(i, 24).Value Then  'Finds correct supplier
        strName = Range("l,13")
        Sheets(strName).Select 'Selects the correct worksheet for the supplier
        For j = 4 To 15 'Month
            If sourceWq.Cells(i, 33).Value = Cells(7, j).Value Then
            For n = 8 To 11 'The type of NCR
                If sourceWq.Cells(i, 27).Value = Cells(n, 2).Value Then
                Cells(n, j).Value = Cells(n, j).Value + 1
                Else: End If
            Next n
            Else: End If
        Next j
        Else: End If
    Next i
Next l

End Sub

2 个答案:

答案 0 :(得分:0)

strName = Range("l,13")应该阅读strName = Cells(l,13)

答案 1 :(得分:0)

我没有使用此循环For i = 2 To 250000(我使用Find方法)稍微重写了您的代码:

Private Sub CommandButton1_Click()

    Dim strName As String
    Dim sourceWq As Worksheet, front As Worksheet, sh As Worksheet
    Dim rng As Range
    Dim firstAddress As String
    Dim wb1 As Workbook, wb2 As Workbook

    Dim l As Long, i As Long, j As Long

    Set wb1 = Workbooks("SD KPIs 2014 onwards")
    Set wb2 = Workbooks("databank progging")

    Set sourceWq = wb1.Worksheets("VQN+Concessionn")
    Set front = wb2.Worksheets("Frontpage")

    For l = 5 To 30
        With sourceWq.Range("X2:X250000")
            Set rng = .Find(front.Cells(l, 13).Value, LookIn:=xlValues)
        End With
        If Not rng Is Nothing Then
            firstAddress = rng.Address
            Do
                strName = front.Cells(l, 13).Value
                Set sh = wb2.Worksheets(strName)
                With sh
                    For j = 4 To 15 'Month
                        If rng.Offset(, 9).Value = .Cells(7, j).Value Then
                            For n = 8 To 11 'The type of NCR
                                If rng.Offset(, 3).Value = .Cells(n, 2).Value Then
                                    .Cells(n, j).Value = .Cells(n, j).Value + 1
                                End If
                            Next n
                        End If
                    Next j
                End With
                Set rng = .FindNext(rng)
            Loop While Not rng Is Nothing And rng.Address <> firstAddress
        End If
    Next l
End Sub