Как открыть файл cvs, где нет контента с VBA? - PullRequest
0 голосов
/ 21 июня 2019

Я должен извлекать данные из SAP при каждой транзакции, каждый раз, когда я делаю транзакцию, я сохраняю ее в файле cvs, я удаляю содержимое на каждом конце транзакции. Проблема в том, что некоторые транзакции могут не иметь данных, и я не знаю заранее, поэтому я удаляю контент в конце каждой транзакции, чтобы он не привязывал данные из старой транзакции к моей таблице Excel.

Ошибка всегда в одном и том же месте,

. Обновить BackgroundQuery: = False

        Sub OpenCSVFile()
        '
        'Load the CSV extract
         '
         '
        With ActiveSheet.QueryTables.Add(Connection:= _
       "TEXT;" & fpath & "\" & ffilename, Destination:=Range("$A$1"))
       .Name = "text"
       .FieldNames = True
       .RowNumbers = False
       .FillAdjacentFormulas = False
       .PreserveFormatting = True
       .RefreshOnFileOpen = False
       .RefreshStyle = xlInsertDeleteCells
       .SavePassword = False
       .SaveData = True
       .AdjustColumnWidth = True
       .RefreshPeriod = 0
       .TextFilePromptOnRefresh = False
       .TextFilePlatform = 850
       .TextFileStartRow = 1
       .TextFileParseType = xlDelimited
       .TextFileTextQualifier = xlTextQualifierDoubleQuote
       .TextFileConsecutiveDelimiter = False
       .TextFileTabDelimiter = True
       .TextFileSemicolonDelimiter = False
       .TextFileCommaDelimiter = False
       .TextFileSpaceDelimiter = False
       .TextFileOtherDelimiter = "|"
       .TextFileColumnDataTypes = Array(1)
       .TextFileTrailingMinusNumbers = True
       .Refresh BackgroundQuery:=False

      End With


      End Sub

       [script]

        Sub StartExtract()

     ' Set the sid and client to connect to
       W_System = "P10320"
    ' Run the GUI script
      RunGUIScript
    ' End the GUI session
      objSess.EndTransaction
     'effacer contenu feuille temp
      Sheets("temp").Select
      Cells.Select
      Selection.Delete Shift:=xlUp
     'Switch to the worksheet where the data is loaded to
      Sheets("temp").Select

      'Load the CSV file
      OpenCSVFile

 Sheets("BGSOCIAL").Select
 Columns("B:G").Select
 Selection.ClearContents
 Sheets("temp").Range("B:G").Copy
 Sheets("BGSOCIAL").Range("B:G").PasteSpecial Paste:=xlPasteValues
 Sheets("BGSOCIAL").Select
 Range("B1").Select
 ActiveCell.FormulaR1C1 = "Poste bilan/compte résultat"
 Range("C1").Select
 ActiveCell.FormulaR1C1 = "Texte pos. bilan/cpte résultat"
 Range("D1").Select
 ActiveCell.FormulaR1C1 = "Total période reporting"
 Range("E1").Select
 ActiveCell.FormulaR1C1 = "Total période de comparaison"
 Range("F1").Select
 ActiveCell.FormulaR1C1 = "Ecart absolu"
 Range("G1").Select
 ActiveCell.FormulaR1C1 = "Ecart relatif"


Workbooks.Open FileName:="C:\Users\p100789\Documents\SAP\SAP GUI\text.txt"
Cells.ClearContents
ActiveWorkbook.Close SaveChanges:=True

End Sub

1 Ответ

0 голосов
/ 21 июня 2019

Вы можете просто проверить, есть ли в файле какие-либо данные, прежде чем начать.

Dim ff As Long
ff = FreeFile
Open fpath & "\" & ffilename For Input As #ff
    If EOF(ff) Then MsgBox "No Data"
Close #ff

Или, если ваш файл содержит заголовки, но не содержит данных

Dim ff As Long
ff = FreeFile
Dim dummy As String
Open fpath & "\" & ffilename For Input As #ff
    If EOF(ff) Then
        MsgBox "No Data"
    Else
        Line Input #ff, dummy 'reads the header row, if it exists
        MsgBox "No Data"
    End If
Close #ff

Есть и другие способы сделать это, но это самый простой

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...