将Excel数据提取到管道分隔文件中 - 如何引用其他工作簿

时间:2014-12-22 11:43:45

标签: excel vba excel-vba

我正在创建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

问题是,&#34;对于每个&#34;循环遍历运行宏的工作簿,而不是打开的宏。我尝试设置该工作簿的活动,但我无法使其工作。任何人都可以帮我设置好吗?

3 个答案:

答案 0 :(得分:1)

Dim Sheet1 as Object    
Set Sheet1 = [Object].Application.Workbooks("filename").WorkSheets("Sheet1")

你也可以这样做

答案 1 :(得分:1)

我需要做类似的事情,虽然在我的情况下,问题的分隔符是>而我正在导入.txt文件,好像它是.csv。

我使用Workbooks.OpenText方法,参数DataType:=xlDelimited。要设置除制表符或逗号或分号以外的分隔符,我将OtherOtherChar参数设置为Other:=True, OtherChar:=">"

这对我有用;也许它对OtherChar:="|"也适用?

答案 2 :(得分:0)

在打开的工作簿中创建对工作表的引用:

Dim sheet As Worksheet
Set sheet = myWkBook.Sheets("Sheet1")

然后在后续代码中使用变量Range/Row/Cell ...属性来防止&#34;裸体&#34; Range默认为ActiveWorkbook

For Each myRecord In sheet.Range("A1:A" & sheet.Range("A" & sheet.Rows.Count).End(xlUp).Row)
    ...