如何遍历工作表中的一列,查找不同的特定字符串,进行设置并复制到第二个工作表中?

时间:2019-07-15 13:45:49

标签: excel vba

我事先进行了编码,然后根据该列的名称将一个工作表中的数据列复制到另一个新工作表中。现在,我要遍历特定列“ FUND”,并使用正确的功能查看其末尾的不同字符,并将其设置为不同的年份。例如,如果它以100结尾,那么我将其更改为2010。

尝试使用if / elseif语句进行for循环。

For i = 1 To Rows.Count
    If Right(sh2.Range("FUND"), 3) = "100" Then
        Set sh2.Cells(i, "FUND") = 2010
    ElseIf Right(sh2.Range("FUND"), 3) = "110" Then
        Set sh2.Cells(i, "FUND") = 2011
    ElseIf Right(sh2.Range("FUND"), 3) = "120" Then
        Set sh2.Cells(i, "FUND") = 2012
    ElseIf Right(sh2.Range("FUND"), 3) = "130" Then
        Set sh2.Cells(i, "FUND") = 2013
    ElseIf Right(sh2.Range("FUND"), 3) = "140" Then
        Set sh2.Cells(i, "FUND") = 2014
    ElseIf Right(sh2.Range("FUND"), 3) = "150" Then
        Set sh2.Cells(i, "FUND") = 2015
    ElseIf Right(sh2.Range("FUND"), 3) = "160" Then
        Set sh2.Cells(i, "FUND") = 2016
    ElseIf Right(sh2.Range("FUND"), 3) = "170" Then
        Set sh2.Cells(i, "FUND") = 2017
    ElseIf Right(sh2.Range("FUND"), 3) = "180" Then
        Set sh2.Cells(i, "FUND") = 2018
    ElseIf Right(sh2.Range("FUND"), 3) = "190" Then
        Set sh2.Cells(i, "FUND") = 2019
    End If
Next

第一个if语句处有一个错误代码:“运行时错误'1004':方法'对象'_Worksheet'的范围失败”

1 个答案:

答案 0 :(得分:0)

与其检查循环中的值,不如检查循环中的值。

类似的事情可能会起作用:

Sub fixFY()
    Dim i As Long
    Dim val as Integer
    If IsNumeric(Right(sh2.Range("FUND"), 3)) Then
        val = CInt(Right(sh2.Range("FUND"), 3)) / 10 + 2000
    Else
        MsgBox "Not a number"
        Exit Sub
    End If

    For i = 1 to sh2.Rows.Count ' Not the best way to determine the last row...
        sh2.Cells(i, "FUND") = val
    Next
End Sub