For Each File in a Folder

I am using for each file in a folder activity to iterate through .crv files and whenever I use (CurrentFile) in any activity as CurrentFile.FullName, it gives me an error that it is workbook application. I also tried debugging and I saw that CurrentFile enters the do container as Null. Does anyone know why is that happening and how can I fix it. I just want to iterate though these crv files and put all of them in a new Excel file, each file in a sheet.

Hi,

Can you share your current workflow and screenshot when the error occurs, if possible?

Regards,

@Menna_Khaled

can you show some screenshots also arethere any two loops or so? or did you create a variable with ame currentfile? ideally in for loop you need not create

cheers

no I just used the automatically created (Current Item)

1 Like

Yes, sure

Hi,

It seems CurrentFile’s type is illegal.
If you define variable named CurrentFile, can you remove it in DataManager or Variable panel?

Regards,


Depending on what version you are using it should be “CurrentFile.FullName” not
“CurrentFile.FilePath” Do you have a variable that’s named FilePath maybe ?
If so don’t use it. Use FullName instead.

Also I see your using excel application scope which is not needed if its a CSV.
You can just use Read CSV like seen below. I have the contents of the CSV outputted just to show it works.

@Menna_Khaled

as mentioned above looks like currentfile is a created variable

in locals panel can you show all your variables please

cheers

@Menna_Khaled

On further thinking you can also put an if statement in to prevent some errors that may come up like the CSV being empty. I’ve created one for an example.

If you were wondering CSVRange is a variable data table that is outputted in Read CSV.

I don’t have another variable with the same name.

I tried CurrentFile.FullName as well and it gave me the same error. currentfile also appears as workbook application but it is supposed to be FileInfo. It actually worked with me as CurrentFile.FullName first but then it gave me an error that is why I tried to make some changes.

Hi,

Can you share your workflow as attached file, if possible?

Regards,

1 Like

Have you put the CSV filter in ?
image
Try putting a message box or a log to command to see the output or you can use a breakpoint in debug mode and use the immediate panel to check the variable value.
You can also try and go to Manage packages and make sure the packages are up to date.
Also remember CSV’s don’t need a Excel Application Scope. You can use read range or read csv activity depending on version. Here’s my version if it helps.
LoopThroughCSVsInFolder.xaml (14.1 KB)

1 Like

I solved it by changing CurrentFIle to Fileinfo in an assign, but I will also check the package as it might be an old version and check your version to know how it should done exactly.. Thank you so much for your support.

I solved it by changing CurrentFIle to Fileinfo in an assign. Thank you so much for your support.

2 Likes

Sub GenerateWordFiles()

'Declare Word application and document objects
Dim wdApp As Object              'Word application instance
Dim wdDoc As Object              'Word document instance

'Paths for template, output folder, and 2nd workbook
Dim TemplatePath As String
Dim SavePath As String
Dim Macro2Path As String

'Excel variables
Dim lastRow As Long, i As Long
Dim contract_keys As String, contract_name As String

'Word Table variables
Dim tbl1 As Object, tbl2 As Object
Dim wb2 As Workbook
Dim wsCP As Worksheet            'Connected Parties sheet
Dim CP_LastRow As Long          'Last row of CP output
Dim CP_Row As Long              'Loop counter
Dim tbl1_Row As Long, tbl2_Row As Long

'Read paths from RUNNNN sheet
''Change below ThisWorkbook.Sheets("RUNNNN") with your Workbook1 sheet name
'''Change H2,J3,J4 to your path addresses
Set wb1 = ThisWorkbook.Sheets("RUNNNN")
TemplatePath = wb1.Range("J4").Value     'Word template
SavePath = wb1.Range("J3").Value         'Output folder
Macro2Path = wb1.Range("J2").Value       '2nd workbook file path
startNum = wb1.Range("J1").Value

'Create output folder if not exists
If Dir(SavePath, vbDirectory) = "" Then MkDir SavePath

'Get last row in column A
lastRow = Cells(Rows.Count, "A").End(xlUp).Row

'Create Word application
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True                                'Show Word

'Open the second workbook containing the macro
Set wb2 = Workbooks.Open(Macro2Path)

'Loop through input rows starting from value in RUNNNN J1
For i = startNum To lastRow
    
    'Read contract values
    contract_keys = wb1.Cells(i, "A").Value
    contract_name = wb1.Cells(i, "B").Value
    
    'Send contract key into wb2
    ''Change sheet name where it want to place the contract_keys, mention that sheet name
    ''If you want to place it in multiple places, copy the same below line code extra and
    ''change the sheet name and range below.
    wb2.Sheets("Sheet1").Range("D2").Value = contract_keys
    
    'Run macro in second workbook
    Application.Run "'" & wb2.Name & "'!PopulateAndSortCPsDetails"
    
    'Set reference to CP output sheet after macro runs
    ''If the output needs to pull from different sheet then change the name below
    ''If the output wants to pull from multiple sheet replace the same line
    ''again below with different Set Variable
    Set wsCP = wb2.Sheets("Connected Parties Check")
    
    'Open the Word template for this contract
    Set wdDoc = wdApp.Documents.Open(TemplatePath)
    
    'Replace the tag with contract name
    ReplaceTag wdDoc, "<<Contract_Name>>", contract_name
    
    '------------------ TABLE PROCESSING BEGINS ----------------------------
    
    'Get references to Table 1 and Table 2
    Set tbl1 = wdDoc.Tables(1)
    Set tbl2 = wdDoc.Tables(2)
    
    'Find last row of data from A11 downward
    CP_LastRow = wsCP.Cells(wsCP.Rows.Count, "A").End(xlUp).Row
    
    '-----------------------------------------------------
    ' TABLE 1 ? Insert/Delete rows based on CP output
    '-----------------------------------------------------
    
    'Ensure table has correct number of rows
    AdjustWordTableRows tbl1, CP_LastRow - 10   'Subtract 10 because data starts at row 11
    
    'Fill Table 1 rows
    tbl1_Row = 2   'Assuming row 1 is header
    
    For CP_Row = 11 To CP_LastRow
        tbl1.Cell(tbl1_Row, 1).Range.Text = wsCP.Cells(CP_Row, "F").Value
        tbl1_Row = tbl1_Row + 1
    Next CP_Row
    
    '-----------------------------------------------------
    ' TABLE 2 ? Only authorised rows (Column M)
    '-----------------------------------------------------
    
    'Clear all existing data rows in Table 2 (except header)
    AdjustWordTableRows tbl2, 0
    
    tbl2_Row = 2
    
    For CP_Row = 11 To CP_LastRow
        
        If wsCP.Cells(CP_Row, "M").Value = "Authorised" Then
        
            'Add new row in Table 2
            tbl2.Rows.Add
            
            'Write Column L value into Table 2
            tbl2.Cell(tbl2_Row, 1).Range.Text = wsCP.Cells(CP_Row, "L").Value
            
            tbl2_Row = tbl2_Row + 1
        End If
    
    Next CP_Row
           
    '------------------ TABLE PROCESSING ENDS ----------------------------
    
    'Construct file name
    ''Here contract_name will be your output extra sub folder will create
    Dim FileName As String
    FileName = SavePath & "\" & contract_name
    
    'Create subfolder if missing
    If Dir(FileName, vbDirectory) = "" Then MkDir FileName
    
    'Final file path
    ''File name will pick first 2 characters
    FileName = FileName & "\CDD_" & Left(contract_name, 2) & ".docx"
    
    'Delete existing file if already exists
    If Dir(FileName) <> "" Then Kill FileName
    
    'Save Word file
    wdDoc.SaveAs2 FileName
    
    'Close Word file
    wdDoc.Close False

Next i

'Quit Word application
wdApp.Quit

MsgBox "All Word files generated successfully!", vbInformation

End Sub

Sub ReplaceTag(doc As Object, findText As String, replaceText As String)
With doc.Content.Find
.Text = findText
.Replacement.Text = replaceText
.Forward = True
.Wrap = 1
.Execute Replace:=2
End With
End Sub

Sub AdjustWordTableRows(tbl As Object, requiredRows As Long)

Dim currentRows As Long
currentRows = tbl.Rows.Count - 1          'Minus header

'Add missing rows
While currentRows < requiredRows
    tbl.Rows.Add
    currentRows = currentRows + 1
Wend

'Remove extra rows
While currentRows > requiredRows And requiredRows >= 0
    tbl.Rows(tbl.Rows.Count).Delete
    currentRows = currentRows - 1
Wend

End Sub

Sub CleanWordTableEmptyRows(tbl As Object)
Dim r As Long

For r = tbl.Rows.Count To 2 Step -1        'Skip header row
    If Trim(tbl.Cell(r, 1).Range.Text) = "" Or _
       Trim(Replace(tbl.Cell(r, 1).Range.Text, Chr(13), "")) = "" Then
        tbl.Rows(r).Delete
    End If
Next r

End Sub

Hi @Menna_Khaled

UiPath has multiple “For Each File”–type activities, and two of them behave very differently:

A. For Each File in Folder (Modern) → OUTPUT TYPE = UiPath.Excel.WorkbookApplication**

  • This activity is primarily meant for Excel files, CSV, XML, etc.
  • It automatically tries to open files using the Excel integration layer.
  • .crv is not an Excel-supported format → the activity treats them as workbook applications → fails → CurrentFile = Nothing

B. For Each File (from System.IO.Directory) → OUTPUT TYPE = String

  • This version gives clean file paths.
  • No auto-opening, no Excel interference.
  • Works with any file extension including .crv.

You most likely used A, which is the root cause.

Use Standard For Each + Directory.GetFiles**

Step-by-step fix

1. Drop a regular For Each Activity

  • Type Argument: String

2. Set Items to:

Directory.GetFiles("C:\Your\Folder\Path", "*.crv")

3. Now you can safely use:

  • item → gives full file path
  • Path.GetFileName(item)
  • Path.GetFileNameWithoutExtension(item)

All without Excel interference.

If you want each CRV file converted into a sheet in an Excel file

You can do something like:

Inside the For Each:

  • Read the .crv content (if applicable)
  • OR convert .crv to PDF/Excel if you have a converter
  • OR simply log the file name into a specific row/sheet

But if .crv is a binary Crystal Reports file, UiPath cannot read its contents directly without:

  • Crystal Reports runtime
  • Export options
  • Or a library to convert it from CRV → Excel/PDF