代码在第二个宏中不起作用

时间:2014-08-27 20:50:15

标签: excel vba excel-vba

我对vba很新,我可以使用一些帮助。  这是我正在使用的代码。这只是一个调用另一个宏和循环的基本宏。但是,它似乎正在跳过从workbooks.openactiveworkbook.saveas的所有内容。  令人讨厌的一点是,我之前使用过两次这段代码,但文件名和路径不同,一切正常。

我已经逐步完成了代码,它实际上似乎正在跳过那些在原始代码中没有做到的行。

Sub oddball_macro_loop()
'
' oddball_macro_loop Macro
'
'

Dim rawPath As String
Dim rawFile As String
Dim savePath As String
Dim oWB As Workbook
Dim fName As Variant


rawPath = "I:\Cores\DMB\E-Prime Tasks\Salience Task\Data\Macros\Raw\For macro"
rawFile = Dir(rawPath & "*.txt")
savePath = "I:\Cores\DMB\E-Prime Tasks\Salience Task\Data\Macros\Processed"

ChDir (rawPath)
Application.DisplayAlerts = True

Do While rawFile <> ""
    Workbooks.Open Filename:="I:\Cores\DMB\E-Prime Tasks\Salience Task\Data\Macros\oddball_macro.xlsm"
    Set oWB = Workbooks.Open(rawPath & rawFile)
    Application.Run "'oddball_macro.xlsm'!oddball_macro"
    Sheets("Data").Select


'Sets File Name
    Dim text As String
    text = Range("Z12")
    fName = Mid(text, 19)
    ActiveWorkbook.SaveAs Filename:=savePath & fName, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWorkbook.Close False
    rawFile = Dir()
Loop

ActiveWorkbook.Close False
Application.ScreenUpdating = True


End Sub

1 个答案:

答案 0 :(得分:2)

如果它正在跳过这些行,则表明Dir()函数的结果为空。

看起来你可能在rawPath的末尾错过了一个路径分隔符?这应该解决它:

rawFile = Dir(rawPath & Application.PathSeparator & "*.txt")

或者只是确保将其添加到作业分配中:

rawPath = "I:\Cores\DMB\E-Prime Tasks\Salience Task\Data\Macros\Raw\For macro\"

通常你会看到人们做这样的事情作为一种仔细检查:

If Not right(rawPath, 1) = Application.PathSeparator then 
    rawPath = rawPath & Application.PathSeparator
End If
rawFile = Dir(rawPath & "*.txt")

或者你可以真正看中并做到这一点:

Dim sep as String
sep = Application.PathSeparator

rawFile = Dir(rawPath & IIF(Right(rawPath,1) = sep, "*.txt", sep & ".txt"))