简体   繁体   English

删除空白列以使用excel-vba创建数据透视表

[英]deleting blank columns to create pivot table using excel-vba

I'm trying to automate the generation of a pivot table for a report I have to write at work. 我正在尝试为必须在工作中编写的报告自动生成数据透视表。 When I import data into excel the data has these extra columns with no information in them. 当我将数据导入excel时,数据中包含这些多余的列,但其中没有信息。 As you probably know, Excel will not create pivot tables when there are extra columsn. 您可能知道,当有多余的列时,Excel不会创建数据透视表。 Is there a script that can delete the columns that have no data? 是否有一个脚本可以删除没有数据的列?

A VBA solution is preferable. VBA溶液是优选的。

有多余列的有损数据的图像

Try this ( TRIED AND TESTED ) 试试这个( 尝试和测试

Sub Sample()
    Dim LastCol As Long
    Dim i As Long

    LastCol = Sheets("Sheet1").Cells.Find(What:="*", _
              After:=Sheets("Sheet1").Range("A1"), _
              Lookat:=xlPart, _
              LookIn:=xlFormulas, _
              SearchOrder:=xlByColumns, _
              SearchDirection:=xlPrevious, _
              MatchCase:=False).Column

    For i = LastCol To 1 Step -1
        If Application.WorksheetFunction.CountA(Sheets("Sheet1").Columns(i)) = 0 Then _
        Sheets("Sheet1").Columns(i).Delete
    Next i
End Sub

FOLLOWUP 跟进

I would recommend Adam's way (It is more efficient) for preparing the data for Pivot as per your requirements. 我建议按照您的要求使用亚当的方法(效率更高)为Pivot准备数据。 My code will fail if there is a blank cell which has a space. 如果空白单元格中有空格,我的代码将失败。 You might want to use 您可能要使用

Len(Trim(ws.Cells(start_row, col).Value)) = 0

in lieu of 替代

ws.Cells(start_row, col).Value = ""

in Adam's code. 用亚当的代码。

If you are sure that there will be no blank space then you can use my code as well :) 如果您确定没有空格,那么也可以使用我的代码:)

Sid 希德

This should be more efficient than @Siddharth's answer because it only checks the first row. 这应该比@Siddharth的答案更有效,因为它仅检查第一行。 (But he beat me by many minutes, so +1 to him!) (但是他打了我好几分钟,所以对他+1!)
Since we know that when there is no column heading, Excel will not allow a pivot table to be created. 由于我们知道没有列标题时,Excel将不允许创建数据透视表。

Option Explicit

Sub prepare_for_pivot()
    Dim ws As Worksheet
    Dim last_col As Long
    Dim start_row As Long
    Dim col As Long
    Set ws = ThisWorkbook.Sheets(1)

    start_row = 1
    last_col = ws.Cells(start_row, ws.Columns.Count).End(xlToLeft).Column

    For col = last_col To 1 Step -1
        If ws.Cells(start_row, col).Value = "" Then
            ws.Columns(col).EntireColumn.Delete
        End If
    Next col
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM