Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

excel - Finding the first row and then deleting the column if it matches the first row

I’m trying to find the first row value of each column. Upon knowing the first value, I want to find whether the column contains the same value as the first row. If yes, I want to delete the entire column.


   lastR = ActiveSheet.Cells(Rows.Count,1).Row
LastC = ActiveSheet.Cells(1, Columns.Count).Column

For i to LastC
FirstRow=ActiveSheet.Range(Cells(4,1),Cells(4,LastC))
End i 

For x= LastC to 1 Step -1
If Worksheet.Function.CountIf(Columns(x), “FirstRow”)= LastR -1 Then 
Columns(x).EntireColumn.Delete 
End If

Next x

End Sub


I have an error 13 in the declaration of firstrow function. Why is it so?

question from:https://stackoverflow.com/questions/65878422/finding-the-first-row-and-then-deleting-the-column-if-it-matches-the-first-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a solution:

Sub Filter()
    Dim rRange As Range
    Dim rRangeColumn As Range
    Dim rRangeColumnData As Range   'Column without header (first cell)
    Dim rFirstCell As Range
    Dim rColumnData As Range   ' without header
    
    Set rRange = ActiveSheet.UsedRange
    For i = rRange.Columns.Count To 1 Step -1
        Set rRangeColumn = rRange.Columns(i)
        With rRangeColumn
            Set rRangeColumnData = Range(Cells(.Row + 1, i), Cells(.Rows.Count + rRange.Row - 1, i))
            Set rFirstCell = .Cells(1, 1)  ' header
            If Application.WorksheetFunction.CountIf(rRangeColumnData, rFirstCell) > 0 Then
                rRangeColumn.EntireColumn.Delete
            End If
        End With
    Next i
End Sub

By the way, your initial code contains an error (For...Next, and i is never used):

For i to LastC
FirstRow=ActiveSheet.Range(Cells(4,1),Cells(4,LastC))
Next i 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...