我正在尝试编写一个在VBA excel中合并两个或更多.dat文件的程序。基本上,它首先要求用户选择任意数量的文件(超过2个)。然后它根据用户选择它们的顺序“合并”文件。通过合并,我的意思是将一个选定的文件附加或复制并粘贴到上一个选定的文件中,并另存为一个全新的文件。我一直坚持创建新变量作为字符串部分,因为我习惯于只打开一个需要打开的文件的打开提示窗口。现在它是基于用户在消息框中选择他是否希望另一个文件与前一个合并的条件。它一直询问这个,直到用户选择否或取消。因此,每次用户选择“是”时,都需要创建一个新变量来存储稍后要打开的文件名。我该如何处理这个过程?还有,一旦用户点击“否”停止合并文件,我如何同时打开所有这些文件,是否有任何聪明的方法来追加或复制和粘贴.dat文件,我尝试过Hex Editor :HxD,如何使用VBA操作Hex Edit程序?
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
谢谢!
答案 0 :(得分: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
参数,但它仅适用于单个目录,并且无法保证所选文件的顺序。