正则表达式 – 使用VBA从文本文件写入excel时保留“列”

前端之家收集整理的这篇文章主要介绍了正则表达式 – 使用VBA从文本文件写入excel时保留“列”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个文本文件,格式如下:

我在VBA中使用以下代码将文本文件写入excel:

  1. Sub Test()
  2.  
  3. Dim Fn As String,WS As Worksheet,st As String
  4.  
  5. Fn = "Path.txt" ' the file path and name
  6. Set WS = Sheets("Sheet1")
  7.  
  8. 'Read text file to st string
  9. With CreateObject("Scripting.FileSystemObject")
  10. If Not .FileExists(Fn) Then
  11. MsgBox Fn & " : is missing."
  12. Exit Sub
  13. Else
  14. If FileLen(Fn) = 0 Then
  15. MsgBox Fn & " : is empty"
  16. Exit Sub
  17. Else
  18. With .OpenTextFile(Fn,1)
  19. st = .ReadAll
  20. .Close
  21. End With
  22. End If
  23. End If
  24. End With
  25.  
  26. 'Replace every two or more space in st string with vbTab
  27. With CreateObject("VBScript.RegExp")
  28. .Pattern = "[ ]{2,}"
  29. .Global = True
  30. .Execute st
  31. st = .Replace(st,vbTab)
  32. End With
  33.  
  34. 'Put st string in Clipboard
  35. With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
  36. .SetText st
  37. .PutInClipboard
  38. End With
  39.  
  40. 'Paste Clipboard to range
  41. WS.Range("A1").PasteSpecial
  42.  
  43. End Sub

我的目标是保留Excel中文文件中的列.

但是,我的代码无法判断计划类型下的空白和福利计划下的空白实际上是两个不同的数据列.它将两列下的空白处理为一个长空格,并且不保留格式.

从视觉上我们知道有列,但我的代码看不到这一点.

有没有办法对此进行编程,以便它识别出文本文件中有两个空格而不是一个大空格?

我想要避免的是必须用字符手动消除它.那可能吗?

假设每列长度为10个字符,我会使用此宽度而不是空格分隔符
  1. Sub FeedTextFileToActiveSheet(ByVal TextFile As String)
  2. Dim i As Integer,Line As String
  3. Open TextFile For Input As #1
  4. While Not EOF(#1)
  5. i = i + 1
  6. Input #1,Line
  7. Range("A" & i) = Trim(Mid(Line,1,10)) 'Business ID
  8. Range("B" & i) = Trim(Mid(Line,11,10)) 'Employee ID
  9. ' ... and so on
  10. Wend
  11. Close #1
  12. End Sub

要使用它,只需调用FeedTextFileToActiveSheet(“Path.txt”)

猜你在找的正则表达式相关文章