VBA知識--如何把excel里的數據寫入txt文本格式


  在日常工作中,我們時常需要提取excel的數據,然后把提取后的數據存入到其它文件里。如果其它文件是excel格式,這個相對比較簡單,這里我們重點講解如何存到txt文本格式里。在碰到這種需求時,我們通常要用到Print函數,下面以實例來闡述。

  某生產工位需要收集數據,然后將數據通過excel模板傳入專用數據庫,供以后的分析使用。下表為數據填寫模板,要求員工在點擊“數據發送”按鈕后,填寫的數據可以存入到特定格式的txt文件。

 

 

 

 

 

 

 

 

 

  • 要求的txt文本格式如下:

#WORKSHOP Shrouds
#MACHINE Blohm1 Clock
#PRODUCT 064-028-111-6-N
#INSPEC 064-028-111-6-OP60
#SPL 05/06/2021 15:58:31
#SN SQ01806-25
#MEASTRACLABEL Operator;331635
Code14_Left;0.01
Code14_Middle;0.01
Code14_Right;0.02
Code15_Left;0.06
Code15_Middle;0.06
Code15_Right;0.07

  •  截取部分代碼進行說明:
Dim oFSO As New FileSystemObject
If oFSO.FolderExists(CstRepDestinationTempOP60) Then Open StrNomFichier For Output As #1 '打開文本文件#1,准備向文本文件寫入字符。
Print #1, "#WORKSHOP " & CstLabelAtelierOP60 Print #1, "#MACHINE " & CstLabelMachineOP60 Print #1, "#PRODUCT " & CstLabelProduitOP60 Print #1, "#INSPEC " & CstLabelGammeOP60 StrDate = Format(Now, "dd/mm/yyyy HH:MM:SS") Print #1, "#SPL " & StrDate Print #1, "#SN " & StrNoOF
      Print #1, "#MEASTRACLABEL " & CstLabelTraceInspectorOP60 & ";" & StrInspector
      '上面7項依次對應上面標准文本的7項

        '開始對代碼的值寫入數據 Print #1, "#MEASTRACLABEL " & CstLabelTraceInspectorOP60 & ";" & StrInspector If StrCode14_Left <> "N/A" Then Print #1, CstLabelCode14_Left & ";" & StrCode14_Left End If If StrCode14_Middle <> "N/A" Then Print #1, CstLabelCode14_Middle & ";" & StrCode14_Middle End If If StrCode14_Right <> "N/A" Then Print #1, CstLabelCode14_Right & ";" & StrCode14_Right End If If StrCode15_Left <> "N/A" Then Print #1, CstLabelCode15_Left & ";" & StrCode15_Left End If If StrCode15_Middle <> "N/A" Then Print #1, CstLabelCode15_Middle & ";" & StrCode15_Middle End If If StrCode15_Right <> "N/A" Then Print #1, CstLabelCode15_Right & ";" & StrCode15_Right End If
Close #1 '------------------------------------------------------------------------------------------------------- '對txt文件進行命名,並存放到指定的文件夾下。(CstRepDestinationTempOP60和CstRepDestinationFinalOP60在前文已經定義指定的文件夾)
GestionFichier.MoveFile CstRepDestinationTempOP60 + "\" + CstLabelGammeOP60 + "_" + StrNoOF + ".txt", CstRepDestinationFinalOP60 + "\" + CstLabelGammeOP60 + "_" + StrNoOF + ".txt"

Set GestionFichier = Nothing '
------------------------------------------------------------------------------------------------------- 
MsgBox "數據已成功發送!"

End If

'嘗試通過txt記錄已經加工的零件編號
Open "\\suz-infr-spc02\SPCVision\Import\Shroud\Backup\1B S2\1.txt" For Append As #1
Print #1, CstLabelMachineOP60 + "\" + StrDate + "\" + StrInspector + "\" + StrNoOF + "\ "
Close #1

 本章節的重點是如何運用print函數進行數據轉存。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM