对过滤的行进行编号

时间:2018-01-27 16:58:29

标签: excel vba filter

我尝试编写一个宏,它执行以下操作:

我有一个包含许多行和列的表,包括一个包含名称的列 喜欢" J63系统"或" J28系统"指定一行中每个部件所属的机器部分。现在我过滤一个系统并查看各个部分:我有一个空列,想要用相同的部件号对所有部件进行编号,每当从一个新的部件号出现时,每次从1开始。

但宏没有正常工作,我无法找出原因:

Option Explicit

Dim i As Integer, n As Integer, k As Integer
Dim system As String
Dim part0 As String, part1 As String

Sub temato()


n = 887
k = 888

Do

part0 = Cells(n, 2)
part1 = Cells(k, 2)


If Cells(k, 36) = "J64 Tail Rotor" Then
    If part1 = part0 Then
        Cells(k, 3) = Cells(k - 1, 3).Value + 1
        n = n + 1
        k = k + 1
        Else
        Cells(k, 3) = 1
        n = n + 1
        k = k + 1
    End If
Else
    k = k + 1
    Debug.Print n
    Debug.Print k
    Do
        'n bleibt
        part1 = Cells(k, 2)
        If Cells(k, 36) = "J64 Tail Rotor" Then
            If part1 = part0 Then
                Cells(k, 3) = Cells(n, 3).Value + 1
                n = k
                k = k + 1
            Else
                Cells(k, 3) = 1
                n = k
                k = k + 1
            End If
        Else
            k = k + 1
        End If

    Loop While Cells(k, 36) <> "J64 Tail Rotor"

End If

Loop While k <= 1260

End Sub

`

1 个答案:

答案 0 :(得分:0)

添加对Microsoft ActiveX Data Objects 6.1 Library的引用,然后复制此宏:

Dim oConn As ADODB.Connection, rs As ADODB.Recordset, sSheet as String
Dim sWorkbookName  as String

sWorkbookName = ThisWorkbook.FullName
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & 
sWorkbookName & """;Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX = 1"""

sSheet="myDataSheet1"
oConn.Open connString
'just an example of SQL, you have to customize it
sSQL = "SELECT [FIELD1], [FIELD2] FROM [" & sSheet & "$] " &  
" WHERE [FIELD1] Like ""*yourmatch"" ORDER BY [FIELD1] ASC"

rs.Open sSQL, oConn, adOpenStatic, adLockOptimistic, adCmdText

'dump results on a temporary sheet or on the data sheet in an empty column
ThisWorkbook.Worksheets("tmp_sheet").Range("A2").CopyFromRecordset rs

rs.Close
oConn.Close 
Set rs = Nothing
Set oConn =  Nothing

发布表结构并指定所需结果后,我将编写SQL查询