【发布时间】:2016-04-15 22:40:26
【问题描述】:
下面的vba 将解析后的输出保存在工作簿中而不是myDir 目录中作为xlsx,我似乎无法弄清楚。它似乎除此之外都起作用,我需要一些专家的帮助来弄清楚最后一部分。基本上,解析myDir 中的每个txt 文件,然后将txt 文件替换为解析后的xlsx。目前,正在发生的事情是myDir 中的第一个txt 文件正在被解析并保存在工作簿中,然后vba 退出。
编辑 下面的 vba 运行,但在工作簿的工作表中显示解析的输出,而不是在 myDir 中保存为 xlsx。
`ActiveWorkbook.SaveAs Filename:=Replace(fn, ".txt", ""), FileFormat:=xlOpenXMLWorkbook'
stepping-through the vba I can see that fn has the full path and the filename but not sure why it does not save to myDir as an xlsx.
VBA
Option Explicit
Private Sub CommandButton21_Click()
Dim myDir As String, fn As String
myDir = "C:\Users\cmccabe\Desktop\EmArray\"
fn = Dir(myDir & "*.txt")
Do While fn <> ""
CreateXLSXFiles myDir & fn
fn = myDir
Loop
End Sub
Sub CreateXLSXFiles(fn As String)
Dim txt As String, m As Object, n As Long, myDir As String
Dim i As Long, x, temp, ub As Long, myList
myList = Array("Display Name", "Medical Record", "Date of Birth", "Order Date", _
"Gender", "Barcode", "Sample", "Build", "SpikeIn", "Location", "Control Gender", "Quality")
myDir = "C:\Users\cmccabe\Desktop\EmArray\"
Sheets(1).Cells.Clear
Sheets(1).Name = CreateObject("Scripting.FileSystemObject").GetBaseName(myDir & fn)
On Error Resume Next
n = FileLen(fn)
If Err Then
MsgBox "Something wrong with " & fn
Exit Sub
End If
On Error GoTo 0
n = 0
txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
With CreateObject("VBScript.RegExp")
.Global = True: .MultiLine = True
For i = 0 To UBound(myList)
.Pattern = "^#(" & myList(i) & " = (.*))"
If .test(txt) Then
n = n + 1
Sheets(1).Cells(n, 1).Resize(, 2).Value = _
Array(.Execute(txt)(0).submatches(0), .Execute(txt)(0).submatches(1))
End If
Next
.Pattern = "^[^#\r\n](.*[\r\n]+.+)+"
x = Split(.Execute(txt)(0), vbCrLf)
.Pattern = "(\t| {2,})"
temp = Split(.Replace(x(0), Chr(2)), Chr(2))
n = n + 1
For i = 0 To UBound(temp)
Sheets(1).Cells(n, i + 1).Value = temp(i)
Next
ub = UBound(temp)
.Pattern = "((\t| {2,})| (?=(\d|"")))"
For i = 1 To UBound(x)
temp = Split(.Replace(x(i), Chr(2)), Chr(2))
n = n + 1
Sheets(1).Cells(n, 1).Resize(, ub).Value = temp
Next
End With
Sheets(1).Copy
ActiveWorkbook.SaveAs Filename:=Replace(fn, ".txt", ""), FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close False
结束子
【问题讨论】:
-
您是否将文件作为文本文件打开?如果是这样,那么当您
SaveAs时,您需要包含文件类型枚举。 -
我刚刚看到您的编辑...看起来您的 MyDir 存在范围问题。它在两个潜艇中都在本地范围内。添加
Option Explicit,你就会明白我的意思了。