简体   繁体   中英

How to loop through a column in a worksheet, look for different specific string, and set them and copy over into the second worksheet?

I coded something beforehand that copied over columns of data in one worksheet into another new worksheet based on the column's name. Now I want to loop through a specific column "FUND" and look at different characters at the end of it with the right function and set it to different years. For example, if it ended in 100, then I would change it to 2010.

Tried doing a for loop with if/elseif statements.

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

There's an error code at the first if statement: "Run-time error '1004': Method 'Range of object'_Worksheet' failed"

Instead of checking the value inside your loop you should do it outside.

Something like this might work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM