我有一个具有随机数量的列和行的excel工作表(列数/行数每次都会改变,以及每列的位置),其中我需要找到标题为“课程信息”的某一列,然后对该列中的所有行/单元格(当然除了标题行)使用CLEAN函数。
我有clean函数的代码:
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代码来计算行数和列数,但除此之外,我遇到了麻烦。
LastRow = ShData.Range(2, Rows.Count).End(xlUp).Row
LastCol = ShData.Range(1, Cols.Count).End(xlToLeft).Column发布于 2019-05-15 18:07:46
使用WorksheetFunction.Match method获取列号。
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发布于 2019-05-15 18:03:30
这里:
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 Subhttps://stackoverflow.com/questions/56146524
复制相似问题