VBA,打开时用“|”分隔excel文件

我有一个macros在Excel中打开.txt文件,是否有一种方法来打开时分隔它们? 注意:多个文件是打开的,所以像“|”分开的活动工作簿,不知道如何分割。 UserInput在我的字典中,是文件select器。

这是我现在有:

Sub Rec() Dim wb As Workbook, fileNames As Object, errCheck As Boolean Dim ws As Worksheet, wks As Worksheet, wksSummary As Worksheet Dim y As Range, intRow As Long, i As Integer ' Turn off screen updating and automatic calculation With Application .ScreenUpdating = False .Calculation = xlCalculationManual End With 'get user input for files to search Set fileNames = CreateObject("Scripting.Dictionary") errCheck = UserInput.FileDialogDictionary(fileNames) If errCheck Then Exit Sub End If For Each Key In fileNames 'loop through the dictionary On Error Resume Next Set wb = Workbooks.Open(fileNames(Key)) If Err.Number <> 0 Then Set wb = Nothing ' or set a boolean error flag End If On Error GoTo 0 ' or your custom error handler Next 'End of the fileNames loop Set fileNames = Nothing ' Reset system settings With Application .Calculation = xlCalculationManual .ScreenUpdating = True .Visible = True End With End Sub 

任何帮助,将不胜感激。

提供您正在使用Excel 2010或更高版本以下应该工作(主要更改到您的WorkBooks.Open语句):

 Sub Rec() Dim fileNames As Object, errCheck As Boolean Dim ws As Worksheet, wks As Worksheet, wksSummary As Worksheet Dim y As Range, intRow As Long, i As Integer ' Turn off screen updating and automatic calculation With Application .ScreenUpdating = False .Calculation = xlCalculationManual End With 'get user input for files to search Set fileNames = CreateObject("Scripting.Dictionary") errCheck = UserInput.FileDialogDictionary(fileNames) If errCheck Then Exit Sub End If For Each Key In fileNames 'loop through the dictionary On Error Resume Next Workbooks.OpenText Filename:=filenames(Key), _ DataType:=xlDelimited, _ Other:=True, _ OtherChar:="|" On Error GoTo 0 ' or your custom error handler Next 'End of the fileNames loop Set fileNames = Nothing ' Reset system settings With Application .Calculation = xlCalculationManual .ScreenUpdating = True .Visible = True End With End Sub 

由于Workbooks.OpenText将显示错误消息,如果它不能打开文件,你可能完全摆脱你的error handling程序(我已经在上面编辑的版本中完成),或者你可以通过设置来禁止OpenText的自动错误消息Application.DisplayAlerts为False,然后继续拥有自己的error handling程序。 (这取决于如果文件不存在,你想要做什么。)

拆分它并循环

 Sub Break_String() Dim WrdArray() As String Dim text_string As String text_string = "A|B|C|D" WrdArray() = Split(text_string, "|") For i = LBound(WrdArray) To UBound(WrdArray) strg = strg & vbNewLine & "Part No. " & i & " - " & WrdArray(i) Next i MsgBox strg End Sub