首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找特定列并清除其下的所有行

查找特定列并清除其下的所有行
EN

Stack Overflow用户
提问于 2019-05-15 17:55:47
回答 2查看 41关注 0票数 0

我有一个具有随机数量的列和行的excel工作表(列数/行数每次都会改变,以及每列的位置),其中我需要找到标题为“课程信息”的某一列,然后对该列中的所有行/单元格(当然除了标题行)使用CLEAN函数。

我有clean函数的代码:

代码语言:javascript
复制
Set Rng = ShData.Range("AB2:AB" & LastRow)

For Each cell In Rng
    cell.Value = Application.WorksheetFunction.Clean(cell.Value)
Next cell

这里的问题是,Rng被设置为列AB,但并不总是该列。我还编写了一个LastRow & LastCol代码来计算行数和列数,但除此之外,我遇到了麻烦。

代码语言:javascript
复制
LastRow = ShData.Range(2, Rows.Count).End(xlUp).Row
LastCol = ShData.Range(1, Cols.Count).End(xlToLeft).Column
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-15 18:07:46

使用WorksheetFunction.Match method获取列号。

代码语言:javascript
复制
Option Explicit

Sub test()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    Dim Col As Double
    On Error Resume Next 'next line throws error if "Course Info" was not found
    Col = Application.WorksheetFunction.Match("Course Info", ws.Rows(1), 0)
    On Error GoTo 0 'always re-activate error reporting

    If Col <> 0 Then 'only do it if "Course Info" was found
        Dim Cell As Range
        For Each Cell In ws.Range(ws.Cells(2, Col), ws.Cells(ws.Rows.Count, Col).End(xlUp))
            Cell.Value = Application.WorksheetFunction.Clean(Cell.Value)
        Next Cell
    End If
End Sub
票数 0
EN

Stack Overflow用户

发布于 2019-05-15 18:03:30

这里:

代码语言:javascript
复制
Option Explicit
Sub Test()

    Dim Rng As Range, Col As Long, cell As Range, LastRow As Long, LastCol As Long

    With ShData
        LastRow = .Range(.Rows.Count, 2).End(xlUp).Row
        LastCol = .Range(1, .Columns.Count).End(xlToLeft).Column
        Col = .Rows(1).Find("Course Info").Column 'this is to find the column number
        Set Rng = .Range(.Cells(2, Col), .Cells(LastRow, Col))
    End With

    For Each cell In Rng
        cell = Application.WorksheetFunction.Clean(cell)
    Next cell

End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56146524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档