VBA导入导出txt

作者:追风剑情 发布于:2014-11-30 20:55 分类:VBA

此文章以项目中的一个实际需求为例

一、工程结构

VBA工程.png

二、UserForm1代码


  1. Private Sub UserForm_Initialize()
  2. lastListIndex = 0
  3. End Sub
  4. Private Sub CommandButton1_Click()
  5. lastListIndex = UserForm1.ComboBox1.ListIndex
  6. ExportConfig (lastListIndex)
  7. End Sub


三、模块1代码


  1. Public Const MaxEdition = 4 '最大语言版本数
  2. Public MaxParamCount As Integer '当前表参数个数
  3. Public paramArr(100) As Variant '当前表参数数组
  4. Public lastListIndex As Integer
  5.  
  6. Sub UIExportConfig()
  7.  
  8. '计算当前表参数
  9. MaxParamCount = 0
  10. For p = 2 To 100 Step 1
  11. If Cells(1, p).Value <> "" Then
  12. paramArr(MaxParamCount) = Cells(1, p).Value
  13. MaxParamCount = MaxParamCount + 1
  14. End If
  15. Next p
  16. '初始化窗体内容
  17. UserForm1.ComboBox1.Clear
  18. Dim cellValue As String
  19. For j = 2 To MaxEdition + 1 Step 1
  20. cellValue = Cells(3, j).Value
  21. UserForm1.ComboBox1.AddItem (Cells(3, j))
  22. Next j
  23. UserForm1.ComboBox1.ListIndex = lastListIndex
  24. UserForm1.Show
  25. End Sub
  26.  
  27. Sub ExportConfig(ByVal editionIndex)
  28. editionIndex = editionIndex + 2
  29. '检测模板文件
  30. Dim curPath As String, path As String
  31. curPath = ThisWorkbook.path & "\" & ActiveSheet.Name & ".txt"
  32. path = ThisWorkbook.path & "\template\" & ActiveSheet.Name & ".txt"
  33. If Dir(path) = Empty Then
  34. MsgBox ("Ä£°åÎļþ²»´æÔÚ" & Chr(10) & path)
  35. Exit Sub
  36. End If
  37.  
  38. '打开模板文件
  39. Const ForReading = 1, ForWriting = 2, ForAppending = 8, TristateFalse = 0
  40. Dim sFile As Object, fso As Object
  41. Set fso = CreateObject("Scripting.FileSystemObject")
  42. Set sFile = fso.OpenTextFile(path, ForReading)
  43. Dim i As Integer, id As Integer
  44. Dim line As String, idStr As String
  45. Dim s As String
  46. s = ""
  47.  
  48. '解析模板文件
  49. Do While Not sFile.AtEndOfStream
  50. line = sFile.ReadLine
  51. i = InStr(1, line, Chr(9))
  52. idStr = Mid(line, 1, i - 1)
  53. id = CInt(idStr)
  54. For p = 0 To MaxParamCount Step 1
  55. line = Replace(line, paramArr(p), Cells(id + 3, editionIndex + MaxEdition * p).Value)
  56. Next p
  57. s = s & line & Chr(13) & Chr(10)
  58. Loop
  59. sFile.Close
  60. Set sFile = Nothing
  61. Set fso = Nothing
  62.  
  63. '生成配置文件
  64. Set fso = CreateObject("Scripting.FileSystemObject")
  65. Set sFile = fso.CreateTextFile(curPath, True, True) '¸²¸ÇÒÑ´æÔÚµÄÎļþ, Unicode±àÂë
  66. sFile.Write (s)
  67. sFile.Close
  68. Set sFile = Nothing
  69. Set fso = Nothing
  70. MsgBox ("成生配置文件完成" & Chr(10) & curPath)
  71. UserForm1.Hide
  72. End Sub


四、运行效果

VBA运行结果.png

标签: VBA

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号