I have this code that works well on my device
Code: Select all
Sub Test()
Dim v, rng As Range, c As Range, coll As Collection, myKey As String, sPath As String, FileName As String, sNationality As String, csvContent As String, lr As Long, f As Long
Application.ScreenUpdating = False
lr = shDB.Cells(shDB.Rows.Count, "S").End(xlUp).Row
Set rng = shDB.Range("S2:S" & lr)
Set coll = New Collection
On Error Resume Next
For Each c In rng
myKey = shDB.Cells(c.Row, "S").Value & "_" & shDB.Cells(c.Row, "T").Value
coll.Add myKey, CStr(myKey)
Next c
On Error GoTo 0
sPath = ThisWorkbook.Path & "\"
For Each v In coll
FileName = sPath & v & ".csv"
f = FreeFile
Open FileName For Output As f
Print #f, "Name,Nationality,Email,Password"
For Each c In rng
If shDB.Cells(c.Row, "S").Value & "_" & shDB.Cells(c.Row, "T").Value = v Then
Select Case shDB.Cells(c.Row, "H").Value
Case 1: sNationality = "مصر"
Case 102: sNationality = "ليبيا"
Case Else: sNationality = Empty
End Select
csvContent = shDB.Cells(c.Row, "D").Value & "," & sNationality
Print #f, csvContent
End If
Next c
Close f
If InStr(v, "_1") > 0 Then
Name FileName As sPath & Replace(v, "_1", "_بنون") & ".csv"
ElseIf InStr(v, "_2") > 0 Then
Name FileName As sPath & Replace(v, "_2", "_بنات") & ".csv"
End If
Next v
Application.ScreenUpdating = True
MsgBox "CSV Files Created Successfully!", vbInformation
End Sub