0

I am trying to rearrange the order of the columns in csv files in a folder on my local drive.

At the moment, from a tutorial, I have found a way to loop through the files. I wanted to cut a column and re insert in a different column. When running this code, Excel is crashing. It seems to be going through duplicate files.

I expected the columns to have moved in all the files in the folder. But they didn't move. And excel is crashing, looks like it's duplicating the files when hitting CTRL + G and running the code.

Here's the code.

Option Explicit

Sub FleetMoveColumns()

    Dim fileDirectory As String
    Dim fileCriteria As String
    Dim fileName As String
    Dim fileToOpen As Workbook
    
    Application.ScreenUpdating = False
    
    fileDirectory = "C:\...\*csv"
    
    fileName = Dir(fileDirectory)
    
    Do While Len(fileName) > 0
    
        Set fileToOpen = Workbooks.Open(fileDirectory & fileName)

        Columns("R").Cut
        Columns("AB").Insert
                
        Debug.Print fileName
    
    Loop
       
    Application.ScreenUpdating = True
    
    
End Sub

Please help.

2
  • 1
    move the *csv from the fileDirectory to the DIr . eg fileDirectory = "C:\...\" and fileName = Dir(fileDirectory & "*csv") Commented Jan 16, 2023 at 15:35
  • You should also fully qualify your Columns ranges with something like fileToOpen.Sheets(1).Columns("R").Cut... Commented Jan 16, 2023 at 15:48

1 Answer 1

1
  1. You need to fully qualify your Columns object with a Worksheet object.
  2. You need to place FileName = Dir within your Do While loop.

Modified code

Do While Len(FileName) > 0

    Set fileToOpen = Workbooks.Open(fileDirectory & FileName)

    ' set the worksheet object
    Set Sht = fileToOpen.Worksheets(1) ' <-- Rename "Sheet1" to your desired worksheet
    
    With Sht
        .Columns("R").Cut
        .Columns("AB").Insert
    End With

    ' clear objects
    Set Sht = Nothing
    Set fileToOpen = Nothing        

    Debug.Print FileName
        
    FileName = Dir
Loop
Sign up to request clarification or add additional context in comments.

2 Comments

@CDP1802 thanks, missed the part it's a .csv file
There are four objects that you need to reference, or Excel won't know what you want to do. Excel Object, Workbook Object, Worksheet Object, and Range Object. See the link below for more details. excelmacromastery.com/vba-objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.