2011-08-17 43 views
1

我正試圖編寫一個程序來合併兩個或多個VBA excel中的.dat文件。基本上,它首先要求用戶選擇任意數量的文件(超過2個)。然後根據用戶選擇的順序「合併」這些文件。通過合併,我的意思是追加或複製並粘貼一個選定的文件到上一個選定的文件,並保存爲一個全新的文件。我一直在創建新的變量作爲字符串部分,因爲我習慣於打開提示窗口彈出一個文件需要打開。現在有條件的基礎是用戶在消息框中選擇他是否希望另一個文件與前一個文件合併。它不斷詢問,直到用戶選擇否或取消。因此,每次用戶選擇「是」時,都需要創建一個新變量來存儲稍後打開的文件名。我如何去做這個過程?還有,如何在用戶點擊「否」停止合併文件的同時打開所有這些文件,並且有任何聰明的方法來追加或複製和粘貼.dat文件,我試過十六進制編輯器:HxD,我如何使用VBA處理十六進制編輯程序?基於條件語句和「合併」.dat文件創建新的字符串變量?

Sub Merge() 
    Dim Response, Message As String 
    Dim File1 As String 'Needs new variable created each time user selects "ok" on msgbox 
    ChDir "C:\" 

File1 = Application.GetOpenFilename(Title:="Select File to be Merged") 
If File1 = "False" Then Exit Sub 
Message = "Select Another File To be Merged With?" 
Response = MsgBox(Message, vbQuestion + vbOKCancel, "Merge Files") 
If Response = vbOK Then 
    'Loop-mechanism to create a new variable each time. HOW? 

Else 
'Open .dat files and start the copy and pasting process HOW with Hex Editor?:I'm using a program called "HxD" 
End If 
End Sub 

謝謝!

回答

1

您可以循環像這樣存儲在一個字符串數組的名字,隨後訪問每一個單獨進行處理:

Sub Merge() 
    Dim File1  As String 'Needs new variable created each time user selects "ok" on msgbox 
    Dim AllFiles() As String 
    Dim count  As Long 

    ChDir "C:\" 

    ReDim AllFiles(0) 

    Do 
     Application.EnableCancelKey = xlDisabled 
     File1 = Application.GetOpenFilename("DAT Files (*.dat),*.dat", 1, "Select File to be Merged") 
     Application.EnableCancelKey = xlErrorHandler 

     If (File1 = "False") Then Exit Do 
     ReDim Preserve AllFiles(count) 
     AllFiles(count) = File1 
     count = (count + 1) 
     If (MsgBox("Select Another File To be Merged With?", vbQuestion + vbOKCancel, "Merge Files") = vbCancel) Then Exit Do 
    Loop 

    If (count = 0) Then 
     MsgBox "No selection" 
     Exit Sub 
    End If 

    For count = 0 To UBound(AllFiles) 
     MsgBox "User selected file name: " & AllFiles(count) 
     '//boogy 
    Next 
End Sub 

GetOpenFilename還支持MultiSelect參數但是它只能在一個單一的目錄和不保證所選文件的順序。

+0

非常感謝,我是新來vba,如果這是c,Id概率。知道如何編寫語法。再次感謝! – jerryh91

+0

嘿,現在我試圖打開存儲在allfile數組中的單個文件,並且遇到麻煩。 – jerryh91

+0

它給我一個錯誤,因爲下標超出範圍:Workbooks.Open Filename:= AllFiles(1) – jerryh91

相關問題