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