我编写了以下函数来查找任何列的最后一行:
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
答案 0 :(得分:1)
我不喜欢过分依赖TryParse
,但这是一种非常出色的工作:
For Each colValue In .Range("F2:F" & GetLastRow(.Cells)) 'Change range as needed
Dim curVal As Integer
If (colValue.Value IsNot Nothing AndAlso Integer.TryParse(colValue.Value.ToString(), curVal)) Then
If curVal > 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
End If
Next
答案 1 :(得分:1)
在使用以下内容之前,请检查单元格值是否为数字:
If IsNumeric(colValue.Value) And colValue.Value > 0 Then
...
答案 2 :(得分:0)
你的答案是使用for语句
Dim fColumn As Integer
fColumn = 6
For i = 2 To GetLastRow(.Cells)
If Cells(i, fColumn).Value > 0 Then
Cells(i, fColumn).Offset(0, -1).Value = "N"
Else
Cells(i, fColumn).Offset(0, -1).Value = "Y"
End If
Next i