Как удалить строки NUL в начале CSV;VBA - PullRequest
0 голосов
/ 10 февраля 2019

У меня есть программа, которая экспортирует спецификацию (см. Пример данных CSV ниже в статье).

Я написал макрос VBA, который использует FileSystemObject для циклического перемещения по выбранной пользователем папке, открывают файлы CSV.для чтения и чтения данных в память с помощью ReadAll, а затем для сохранения и сортировки данных в excel.

Проблема, с которой я столкнулся, заключается в том, что после экспорта файлов CSV я запускаю макрос и текст в файле CSV сохраняетсяв моей строковой переменной (sTemp в коде ниже) в виде нескольких квадратных скобок.Я скопировал значение строковой переменной и вставил его в текстовый редактор, и он выглядит как несколько повторяющихся черных ящиков, содержащих «SOH».Поскольку данные читаются неправильно, макрос завершается с ошибкой.

Если я открою исходный файл CSV, первые два символа будут черными ящиками с надписью «NUL».NUL NUL "Узор", "Кол-во", "Размер", "Материал", "Описание", "Длина (футы)" 2041 ,, "3", "", "316L Stainless Sch 10S PE", 20 2041 ,,«3», «», «316L Stainless Sch 10S PE», 2,21 5044,1, «3», «Нержавеющая сталь: 304L», «DET S10 SS BUTT WELD», 2523,1, «3», «Нержавеющая сталь»: 316L "," 316L-SS-SCH10 Короткий радиус 90 ", 2522,1," 3 "," Нержавеющая сталь: 304L "," DET S10 SS BUTT WELD ",

Если я сохраню файлы CSVв Excel закройте их, два символа «NUL» пропали: «Шаблон», «Кол-во», «Размер», «Материал», «Описание», «Длина (футы)» 2041 ,, «3», «»,"Нержавеющая сталь 316L Sch 10S PE", 20 2041 ,, "3", "", "Нержавеющая сталь 316L Sch 10S PE", 2,21 5044,1, "3", "Нержавеющая сталь: 304L", "DET S10 SS BUTT WELD", 2523,1, «3», «Нержавеющая сталь: 316L», «316L-SS-SCH10 Короткий радиус 90», 2522,1, «3», «Нержавеющая сталь: 304L», «DET S10 SS BUTT WELD»,

После запуска макроса для сохраненных файлов строковая переменная (sTemp в приведенном ниже коде) содержит правильный текст в файле CSV.

Я хотел бы знать, как исключить NULструны в началеng CSV и хотел бы избежать открытия и сохранения программных файлов CSV, если это вообще возможно.

'Variables for accessing and cleaning text files
Dim oFSO As FileSystemObject 'File System Object grants access to computer files and folders
Dim sSourceFolder As String 'Path of oSourceFolder
Dim oSourceFolder 'Folder the original CSV file is stored in
Dim oFile 'The orignal CSV
Dim sFileToCopy As String 'Path of the copied CSV
Dim sTargetFolder As String 'The path of oTargetFolder
Dim oTargetFolder 'The folder the new CSV file is stored in
Dim oCopiedText 'The copied text file
Dim oCopiedFile 'The copied file itself
Dim oInput 'Represents the text in the CSV ror readin in CSV to memory
Dim sTemp As String 'For storing CSV data in memory
Dim cFiles As New Collection 'Storage for all the files in all the sub folders
Dim sPath As String 'The path of one of the files, will be reused for each file

'variables for progress
Dim iFiles As Integer
Dim Progress As Double

'Constants for reading and writing to text files
Const ForReading = 1
Const ForWriting = 2

'File System Object grants access to computer files and folders
Set oFSO = CreateObject("Scripting.FileSystemObject")

'Select the folder to get CSV files from
sSourceFolder = GetFolder("C:\", "Select Folder Containing CSV files")
Set oSourceFolder = oFSO.GetFolder(sSourceFolder) 'Tell File System Object to get a hold of oSourceFolder so you can look into it

'Check/create the _Cleaned folder inside of the source folder
On Error Resume Next
Err.Clear
sTargetFolder = oSourceFolder.Path & "\" & oSourceFolder.Name & "_Cleaned"
Set oTargetFolder = oFSO.GetFolder(sTargetFolder)
If Err.Number <> 0 Then
    'create the folder
    oTargetFolder = oFSO.CreateFolder(sTargetFolder)
End If
On Error GoTo 0

'Loop through and clean each CSV so it can be opened in excel properly
iFiles = oSourceFolder.Files.Count
Progress = 0

For Each oFile In oSourceFolder.Files 'go through each file
    Application.StatusBar = "Progress: " & Progress & " of " & CStr(iFiles) & ": " & Format(Progress / iFiles, "0%")
    If Right(oFile, 3) = "csv" Then   'if it is a text file...
        'Copy the original file path
        sFileToCopy = oFile.Path

        'Open txt file in memory
        Set oInput = oFSO.OpenTextFile(sFileToCopy, ForReading)

        'Input txt from file to memory
        sTemp = oInput.ReadAll
        'sTemp contains a repeating SOH string if I do not save the files first and the macro fails downstream
        'If I open the CSV file in excel, save it, close it, then run the macro, sTemp contains the string data in the file and the macro runs fine

'Могу ли я как-то удалить строки NUL на этом этапе?,,.

Я ожидаю, что значение sTemp будет считывать фактический текст в файле CSV: «Шаблон, Кол-во, Размер, Материал, Описание, Длина (футы) 2041,, 3,, 316L Нержавеющая сталь Sch 10S PE, 20"

Вместо этого значение sTemp в окне VBA locals:" [[[[[[[[[[[[[[[[[[[[[[[[[]и вставьте его в текстовый редактор, который гласит: «1 SOH SOH SOH SOH SOH SOH»

Файлы сохраняются здесь: https://www.dropbox.com/sh/e8ohn61bxqidejd/AAB9CMno8N_EXdlA83TBX602a?dl=0.

Любая помощь приветствуется.

1 Ответ

0 голосов
/ 11 февраля 2019

У вас есть файл с первыми двумя символами как ASCI 0.

Это два основных параметра:

  1. Исправлен экспорт, который создал эти файлы, чтобы не генерироватьNULL или
  2. Обрезать начальные символы NULL.

Для варианта 2 кажется, что ReadAll завершается неудачно, но ReadLine работает.

Демонстрация удаления значений NULL

Sub Demo()
    Dim oFSO As FileSystemObject
    Dim oInput As TextStream
    Dim sTemp

    Set oFSO = New FileSystemObject
    Set oInput = oFSO.OpenTextFile("Your\File.csv")
    sTemp = oInput.ReadLine
    Do While Left$(sTemp, 1) = Chr(0)
        sTemp = Mid$(sTemp, 2)
    Loop
    Do Until oInput.AtEndOfStream
        sTemp = sTemp & vbCrLf & oInput.ReadLine
    Loop
End Sub
...