Guest User

Untitled

a guest
Mar 20th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. Sub CSVFileAsUTF8WithoutBOM()
  2. Dim SrcRange As Range
  3. Dim CurrRow As Range
  4. Dim CurrCell As Range
  5. Dim CurrTextStr As String
  6. Dim ListSep As String
  7. Dim FName As Variant
  8. Dim UTFStream As Object
  9. Dim BinaryStream As Object
  10.  
  11. ' ask for file name and path
  12. FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv")
  13.  
  14. ' prepare UTF-8 stream
  15. Set UTFStream = CreateObject("adodb.stream")
  16. UTFStream.Type = adTypeText
  17. UTFStream.Mode = adModeReadWrite
  18. UTFStream.Charset = "UTF-8"
  19. UTFStream.LineSeparator = adLF
  20. UTFStream.Open
  21.  
  22. 'set field separator
  23. ListSep = ","
  24. 'set source range with data for csv file
  25. If Selection.Cells.count > 1 Then
  26. Set SrcRange = Selection
  27. Else
  28. Set SrcRange = ActiveSheet.UsedRange
  29. End If
  30.  
  31. For Each CurrRow In SrcRange.Rows
  32. 'enclose each value with quotation marks and escape quotation marks in values
  33. CurrTextStr = ""
  34. For Each CurrCell In CurrRow.Cells
  35. CurrTextStr = CurrTextStr & """" & Replace(CurrCell.Value, """", """""") & """" & ListSep
  36. Next
  37. 'remove ListSep after the last value in line
  38. While Right(CurrTextStr, 1) = ListSep
  39. CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
  40. Wend
  41. 'add line to UTFStream
  42. UTFStream.WriteText CurrTextStr, adWriteLine
  43. Next
  44.  
  45. 'skip BOM
  46. UTFStream.Position = 3
  47.  
  48. 'copy UTFStream to BinaryStream
  49. Set BinaryStream = CreateObject("adodb.stream")
  50. BinaryStream.Type = adTypeBinary
  51. BinaryStream.Mode = adModeReadWrite
  52. BinaryStream.Open
  53.  
  54. 'Strips BOM (first 3 bytes)
  55. UTFStream.CopyTo BinaryStream
  56.  
  57. UTFStream.Flush
  58. UTFStream.Close
  59.  
  60. 'save to file
  61. BinaryStream.SaveToFile FName, adSaveCreateOverWrite
  62. BinaryStream.Flush
  63. BinaryStream.Close
  64.  
  65. End Sub
  66.  
  67. Const adTypeText = 2
  68. Const adModeReadWrite = 3
  69. Const adTypeBinary = 1
  70. Const adLF = 10
  71. Const adSaveCreateOverWrite = 2
  72. Const adWriteLine = 1
Add Comment
Please, Sign In to add comment