使用特定的列值创建表

时间:2018-08-05 09:40:44

标签: excel vba excel-vba

让我们再尝试一次。我有一列这样的数据:

First Table

现在,我需要一个代码来检查该列,省略特定值,即。 “开始”,“结束”,“否”,“ ”。如果该值不等于“开始”,“结束”,“否”,“ ” 而不是我想转置这些值以创建一个像这样的表:

Second Table

对于代码,我发现了这一点,并根据自己的目的对其进行了调整。它不起作用,因为它不会忽略不需要的值,而是删除它们所在的行,所以我猜它可能对我有用。仍然想知道如何将其转置到表格​​中。

Sub Deleteunwanted()

Dim lRow As Long
Dim iCntr As Long
lRow = 17
For iCntr = lRow To 1 Step -1
    If Cells(iCntr, 1) = "Start" Or Cells(iCntr, 1) = "*" Or Cells(iCntr, 1) = "NO" Or Cells(iCntr, 1) = "END" Then
    Range("A" & iCntr).Delete Shift:=xlUp
    End If


Next

End Sub

2 个答案:

答案 0 :(得分:0)

尝试此代码

import pandas as pd
data = pd.read_excel('file.xlsx')
mydf = data.groupby[['First','Second']].sum()

答案 1 :(得分:0)

我认为仍然需要回答一些问题(请参阅我的评论),但以下是一些假设的起点。

1)我将输出表的列数保留在一个常量变量中,以便您可以选择所需的列数:

Const numberOfColumnsInTable = 4

2)我列出了要忽略的项目列表并将其存储在数组中,以便您可以轻松扩展/修改选择范围:

wordsToExclude = Array("NO", "*", "Start", "END")

3)我将所有列数据存储在从图纸读取的2D数组中。这比循环处理工作表要快得多。

4)我循环输入数组的第一维(arrayIn),检查是否在数组中找到了当前值。如果未找到,将引发我检查的错误。

IsError(Application.Match(arrIn(i, 1), wordsToExclude, 0))

如果出错,则保留该值并将其存储在输出数组(arrayOut)中。

5)我将输出数组重新划分尺寸,只填充到填充的行,然后写入工作表。


代码:

Option Explicit
Public Sub OrderInTable()
    Dim ws As Worksheet, arrIn(), arrOut(), i As Long, wordsToExclude(), rowCounter As Long, columnCounter As Long
    Dim counter As Long
    Const numberOfColumnsInTable = 4

    wordsToExclude = Array("NO", "*", "Start", "END")
    Set ws = ThisWorkbook.Worksheets("Sheet13")

    With ws
        arrIn = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row).Value
        ReDim arrOut(1 To UBound(arrIn, 1), 1 To numberOfColumnsInTable)
        For i = LBound(arrIn, 1) To UBound(arrIn, 1)
            If IsError(Application.Match(arrIn(i, 1), wordsToExclude, 0)) Then
                counter = counter + 1
                If counter Mod numberOfColumnsInTable = 1 Then
                    rowCounter = rowCounter + 1: columnCounter = 1
                Else
                   columnCounter = columnCounter + 1
                End If
                arrOut(rowCounter, columnCounter) = arrIn(i, 1)
            End If
        Next
        arrOut = Application.WorksheetFunction.Transpose(arrOut)
        ReDim Preserve arrOut(1 To numberOfColumnsInTable, 1 To rowCounter)
        arrOut = Application.WorksheetFunction.Transpose(arrOut)

        .Range("C1").Resize(UBound(arrOut, 1), UBound(arrOut, 2)) = arrOut
    End With
End Sub