【发布时间】:2014-12-22 11:43:44
【问题描述】:
我正在创建 excel 文件,其中仅包含一个按钮,当单击该按钮时,将指定(现在只是硬编码)目录中的所有其他 excel 文件提取到管道分隔的 .txt 文件中。我以前做过一些编程,但我对 VBA 不太熟悉,所以我通常通过搜索和重用教程等来工作。
基本上我想做的是: - 遍历特定目录 - 对于每个 xls/xlsx 文件,使用 .txt 扩展名创建单独的 .txt 管道分隔的同名提取
到目前为止,我得到了这段代码:
Sub Run_Coversion()
Dim directory As String
Dim fileName As String
Dim OutputFile As String
Dim myWkBook As Workbook
Dim myRecord As Range
Dim myField As Range
Dim nFileNum As Long
Dim sOut As String
Const DELIMITER As String = "|"
Application.ScreenUpdating = False
directory = "C:\Users\vacek\Documents\EFPIA_Project\Excel_Tool\Files\"
fileName = Dir(directory & "*.xls*")
Do While fileName <> ""
Workbooks.Open (directory & fileName)
OutputFile = directory & fileName & ".txt"
nFileNum = FreeFile
Open OutputFile For Output As #1
Set myWkBook = Workbooks(fileName)
myWkBook.Sheets("Sheet1").Activate
For Each myRecord In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
With myRecord
For Each myField In Range(.Cells, Cells(.Row, Columns.Count).End(xlToLeft))
sOut = sOut & DELIMITER & myField.Text
Next myField
Print #nFileNum, Mid(sOut, 2)
sOut = Empty
End With
Next myRecord
End With
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
End Sub
问题是,“For each”循环通过运行宏的工作簿,而不是打开的那个。我尝试过将该工作簿设置为活动状态,但无法使其正常工作。谁能帮我设置一下?
【问题讨论】: