我编写了以下函数来查找任何列的最后一行:
Public Function GetLastRow(ByVal rngToCheck As Excel.Range) As Long
Dim rngLast As Excel.Range
rngLast = rngToCheck.Find(What:="*", SearchOrder:=Excel.XlSearchOrder.xlByRows, SearchDirection:=Excel.XlSearchDirection.xlPrevious)
If rngLast Is Nothing Then
GetLastRow = rngToCheck.Rows.Count
Else
GetLastRow = rngLast.Rows.Count
End If
End Function
每当我处理动态范围时,我都会使用此功能,这在我的项目中是多次的。现在,我想找到 F 列的最后一行,但从 F2 开始。它必须忽略 F1 行,因为那是标题。但是,它不是,我得到一个错误,它无法从 String 转换为 Double,这是预期的,因为 F1 是一个字符串(列标题),而其他所有内容都是数据。
我不想更改我的功能,因为在某些情况下,我需要从第 1 行向下,有时从第 2 行向下,这是我认为我在下面的代码中所做的,但它不起作用,它一直在读取 F1当然会出错,因为 F1 是一个字符串,而该列的其余部分是 Double。
Dim xlWB As Excel.Workbook = CType(Globals.ThisWorkbook.Application.ActiveWorkbook, Excel.Workbook)
Dim xlWSEmployee As Excel.Worksheet = CType(CType(xlWB.Sheets("byEmployee"), Excel.Worksheet), Excel.Worksheet)
Dim xlWSPosition As Excel.Worksheet = CType(CType(xlWB.Sheets("byPosition"), Excel.Worksheet), Excel.Worksheet)
Sub renameColumns()
With xlWSPosition
Dim colValue As Excel.Range
For Each colValue In .Range("F2:F" & GetLastRow(.Cells)) 'Change range as needed
If colValue.Value > 0 Then
'used offset instead of range,ie (E1:E)
.Range(colValue.Address).Offset(0, -1).Value = "N"
Else
.Range(colValue.Address).Offset(0, -1).Value = "Y"
End If
Next
End With
End Sub