0

我编写了以下函数来查找任何列的最后一行:

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
4

3 回答 3

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
于 2013-09-17T21:32:33.990 回答
1

在将其与以下内容一起使用之前,请检查单元格值是否为数字:

If IsNumeric(colValue.Value) And colValue.Value > 0 Then
  ...
于 2013-09-17T21:34:05.167 回答
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
于 2013-09-17T21:52:24.787 回答