2012-11-08 60 views
1

在当前目录下的文件,我有一个Excel工作表一个文件夹中,并尝试使用下面的代码此文件夹中合并某些文件到一个文件:VBA合并使用的cmd.exe

Private Sub CommandButton1_Click() 
    Dim RET As Variant 
    RET = Shell("cmd.exe copy files1.txt + file2.txt out.txt", 0) 
End Sub 

至于返回值RET我得到1560.调试时没有错误,但也没有“out.txt”。 我的代码有什么问题?谢谢

回答

2

我想你错过了cmd参数和路径中的/ C.

Private Sub CommandButton1_Click() 
    Dim RET As Variant 
    RET = Shell("cmd.exe /C copy C:\Data\files1.txt + C:\Data\file2.txt C:\Data\out.txt", 0) 
End Sub 

返回值不等于0表示处理开始(它是实际的进程id)

+0

我试过有和没有,问题依然存在。 – Lumpi

+0

可以试试cmd/c echo hallo> out.txt – rene

+0

没有创建文件... – Lumpi

1

的VBA方式;

Function readFile(path) As String 
    On Error GoTo ERR_IO 
    Dim hF As Integer: hF = FreeFile 
    Open path For Input As #hF 
    readFile = Input$(LOF(hF), hF) 
ERR_IO: 
    Close #hF 
End Function 

Function writeFile(path, buffer) As Boolean 
    On Error GoTo ERR_IO 
    Dim hF As Integer: hF = FreeFile 
    Open path For Output As #hF 
    Print #hF, buffer 
    writeFile = True 
ERR_IO: 
    Close #hF 
End Function 

Sub merge() 
    Dim buffer As String 
    buffer =   readFile("C:\xxx\files1.txt") 
    buffer = buffer & readFile("C:\xxx\files2.txt") 

    writeFile "c:\xxx\out.txt", buffer 
End Sub