Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

IF statement executing even though condition is false

0

I'm checking a collumn if it has an X if it has an X then it should copy the second collumn of the same line.

The problem I'm having is that it sometimes copies the second collumn even if there isn't an X in that line

<    For i = 99 To 528 Step 1

        'Zadnja vrstica na novem listu

        raw_last_row = Sheets("Št. orodja").Cells(Rows.Count, 1).End(xlUp).Row

        If Sheets("BIG_FAMILY_227227_AKTUALNO").Cells(i, 23).Value = "X" Then

        Sheets("BIG_FAMILY_227227_AKTUALNO").Cells(i, 2).Copy Sheets("Št. orodja").Cells(raw_last_row + 1, 1)

        End If

    Next i

>

Answer
Discuss

Discussion

Next time, please use the CODE button and paste your code to replace the text "Code_Goes_Here". It will then appear like the code in my Answer (and be helpfully presented and easier for you and others to copy)
John_Ru (rep: 6142) Jul 27, '22 at 4:32 am
Add to Discussion

Answers

0

Hi and welcome to the Forum.

I can't see a problem with your code in the file I have created to run your code (normally you should use the Add Files... button to upload a representative Excel file (without any personal data) to show your existing macro and data).

I've modified your code only to change the size of the loop and add loops (chnages in bold below):

Sub CopyXcell()

    For i = 1 To 10 'Step 1 ' Note: step of 1 is the default so can be omitted
        'Zadnja vrstica na novem listu
        raw_last_row = Sheets("Št. orodja").Cells(Rows.Count, 1).End(xlUp).Row

        If Sheets("BIG_FAMILY_227227_AKTUALNO").Cells(i, 23).Value = "X" Then
            ' copy column 2 to column 1 of other sheet
            Sheets("BIG_FAMILY_227227_AKTUALNO").Cells(i, 2).Copy Sheets("Št. orodja").Cells(raw_last_row + 1, 1)
        End If
    Next i

End Sub

Once you've checked the second sheet is empty, you can run the code by clicking the button called Copy B if W="X" in sheet "BIG_FAMILY_227227_AKTUALNO".

It copies (with formats) only cells B2 and B5 to the second sheet (since W2 and W5 are "X").

If you're still having problems, you can used Step Into under the Debug menu of VB Project Explorer to tep through your code line by line (by pressing F8) to see what is happening.

Hope this helps (if so, please remember to mark this Answer as Selected).

Discuss


Answer the Question

You must create an account to use the forum. Create an Account or Login