gpt4 book ai didi

regex - 使用 VBA 从文本文件写入 Excel 时保留 "columns"

转载 作者:行者123 更新时间:2023-12-02 04:00:45 25 4
gpt4 key购买 nike

我有一个文本文件,其格式如下:

enter image description here

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

Sub Test()

Dim Fn As String, WS As Worksheet, st As String

Fn = "Path.txt" ' the file path and name
Set WS = Sheets("Sheet1")

'Read text file to st string
With CreateObject("Scripting.FileSystemObject")
If Not .FileExists(Fn) Then
MsgBox Fn & " : is missing."
Exit Sub
Else
If FileLen(Fn) = 0 Then
MsgBox Fn & " : is empty"
Exit Sub
Else
With .OpenTextFile(Fn, 1)
st = .ReadAll
.Close
End With
End If
End If
End With

'Replace every two or more space in st string with vbTab
With CreateObject("VBScript.RegExp")
.Pattern = "[ ]{2,}"
.Global = True
.Execute st
st = .Replace(st, vbTab)
End With

'Put st string in Clipboard
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.SetText st
.PutInClipboard
End With

'Paste Clipboard to range
WS.Range("A1").PasteSpecial

End Sub

我的目标是在 Excel 中保留文本文件中的列。

但是,我的代码无法判断 Plan Type 下的空格和 Benefit Plan 下的空格实际上是两列不同的数据。它将两列下的空格视为一个长空格,并且不保留格式。

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

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

我想避免的是必须用字符手动分隔它。这可能吗?

最佳答案

假设每列的长度为 10 个字符,我将使用此宽度而不是空格分隔符

Sub FeedTextFileToActiveSheet(ByVal TextFile As String)
Dim i As Integer, Line As String
Open TextFile For Input As #1
While Not EOF(#1)
i = i + 1
Input #1, Line
Range("A" & i) = Trim(Mid(Line, 1, 10)) 'Business ID
Range("B" & i) = Trim(Mid(Line, 11, 10)) 'Employee ID
' ... and so on
Wend
Close #1
End Sub

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

关于regex - 使用 VBA 从文本文件写入 Excel 时保留 "columns",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52863383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com