Absolutely nothing wrong with sudbhavani's code but since you are using a Table for your data I'd suggest you use the Table Object Properties to determine rows and columns to write csv lines.
Sub btnSaveDataCSV_Click()
Dim folderPath As String, _
csvFileName As String, _
shtObject, _
dataRow As Long, _
dataCol As Long, _
csvLine As String
' Get folder path and file name from the "Main" sheet
folderPath = Range("CITable")
If folderPath = "" Then
MsgBox "Folder path is empty. Please specify a valid folder path in cell A2.", vbCritical, "Error"
Exit Sub
End If
' Ensure folder path ends with a backslash
If Right(folderPath, 1) <> "\" Then
folderPath = folderPath & "\"
End If
' Check if folder exists
If Dir(folderPath, vbDirectory) = "" Then
MsgBox "The specified folder does not exist: " & folderPath, vbCritical, "Error"
Exit Sub
End If
' Set file name from cell C2 in the "Main" sheet
csvFileName = folderPath & Range("CsvName") & ".csv"
' Create the ADODB stream for UTF-8 encoding
With CreateObject("ADODB.Stream")
.Type = 2 ' Text
.Charset = "UTF-8"
.Open
' Loop through rows and columns to write the CSV content
shtObject = Sheets("Data").ListObjects(1).DataBodyRange
For dataRow = 1 To UBound(shtObject)
csvLine = "" ' Start a new CSV line
For dataCol = 1 To UBound(shtObject, 2)
csvLine = csvLine & shtObject(dataRow, dataCol) & "," ' Add column data
Next dataCol
csvLine = Left(csvLine, Len(csvLine) - 1) ' Remove the last comma
.WriteText csvLine & vbCrLf ' Write the line to the stream
Next dataRow
' Save the file
.SaveToFile csvFileName, 2 ' Overwrite if the file already exists
.Close
End With
' Clean up
MsgBox "File saved successfully as UTF-8: " & csvFileName, vbInformation, "Success"
End Sub
Bookmarks