如果单元格值为0,则删除列,Excel VBA - 删除所有列

时间:2015-11-12 21:31:37

标签: excel vba excel-vba

如果该列中的某个单元格是" 0"我试图删除列。 - 我循环遍历所有工作表。我尝试了不同的变体,但最终会得到不同的结果 - 要么没有删除,要么删除所有内容。

整个代码:

Sub Finalize()
Dim finalform As Worksheet
Dim deletename As String
Dim finalworkbook As Workbook
Dim ws As Worksheet
Dim copyrange As Range
Dim columnloop As Range
Dim finalarray As Variant

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Set finalform = Workbooks(ActiveWorkbook.Name).ActiveSheet

finalarray = Array(finalform.Range("D3").Value, finalform.Range("D4").Value, finalform.Range("D5").Value _
, finalform.Range("D6").Value, finalform.Range("D7").Value, finalform.Range("D8").Value, finalform.Range("D9").Value _
, finalform.Range("D10").Value, finalform.Range("D11").Value, finalform.Range("D12").Value, finalform.Range("D13").Value _
, finalform.Range("D14").Value, finalform.Range("D15").Value)

On Error Resume Next
For a = 3 To 20

If Range("B" & a).Value <> "" Then
    Workbooks.Open finalform.Range("B" & a).Value
    Set finalworkbook = Workbooks(ActiveWorkbook.Name)

        'Find, replace, remove
        For Each ws In finalworkbook.Worksheets

            'Copy paste values
            If Not IsInArray(ws.Name, finalarray) Then
                Set copyrange = ws.Cells
                copyrange.Copy
                copyrange.PasteSpecial xlPasteValues
            End If
            Application.CutCopyMode = False

        Next ws

        For Each ws In finalworkbook.Worksheets
            'Delete sheets
            For b = 3 To 15
                deletename = finalform.Range("D" & b).Value
                If deletename <> "" Then
                    finalworkbook.Worksheets(deletename).Delete
                End If
            Next b

            With ws
                myChar = Chr(10)
                'Enter space
                .UsedRange.Replace What:="~~", Replacement:=myChar, LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                ReplaceFormat:=False

                For c = .UsedRange.Columns.Count To 1 Step -1
                    cName = Split(Cells(, c).Address, "$")(1)
                    nom = .Range(cName & "8").Value
                    If nom = 0 Then
                        .Columns(c).EntireColumn.Delete
                    End If
                Next c
            End With
        Next ws

        finalworkbook.Save
        finalworkbook.Close
End If
Next a

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

2 个答案:

答案 0 :(得分:0)

这里的问题是VBA如何解释= 0操作。这是一个快速列表。你最有可能想像ZygD所说的那样使用IsEmpty()。

IsEmpty(cell.Value) 'Returns true if the cell is empty, or false if it is filled with 0.

cell.Value = 0 'Returns true if the cell is empty and if it is filled with 0, false otherwise.

IsNumeric(cell.Value) 'Returns true if the cell is empty, or if it is filled with any number, false otherwise.

答案 1 :(得分:0)

如果您循环浏览所有工作表,您甚至可以使用vbNullString而不是0或“”,因为它运行得更快。