使用其他分隔符“=”

时间:2017-10-25 09:57:04

标签: vba excel-vba delimiter excel

尝试将文本文件导入Excel时遇到问题。我编写了一个VBA代码,它使用以下分号分隔符完美地处理导入。

  

但是,当我尝试包含其他分隔符(在我的情况下等于)时

  

=

它给我一个错误。

  

对象'Workbooks'的方法'Open Text'失败。

请查找附带我的示例文本文件,该文件通常具有扩展名.cfg

Dos-001-Zykl_Date_r(V1.0)=1401174131;27.05.2014 07:02:11;
Dos-002-Zykl_Date_r(V1.0)=1401174225;27.05.2014 07:03:45;

及其相应的VBA代码

Sub ImportTextFile()
'Imports a text file
Dim vFileName

On Error GoTo ErrorHandle

 vFileName = Application.GetOpenFilename()

'If the user pressed "Cancel" or didn't select a text file,
'exit the procedure.
If vFileName = False Then
   GoTo BeforeExit
End If

'Switch off screen updating for speed.
Application.ScreenUpdating = False

'We now import the selected text file, and data is
'inserted in a new spreadsheet. If you want to use
'another delimiter, you must change "Semicolon:=True"
'to "Semicolon:=False" and set another delimiter
'(e.g. "Tab") to True.
Workbooks.OpenText Filename:=vFileName, _
    Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
    xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, _
    Comma:=False, Space:=False, Other:=False, _
    TrailingMinusNumbers:=True, Local:=True

'Just to show how we auto adjust the width of column A.
Columns("A:A").EntireColumn.AutoFit

BeforeExit:
Application.ScreenUpdating = True
Exit Sub
ErrorHandle:
MsgBox Err.Description
Resume BeforeExit
End Sub

建议,想法对解决这个问题非常有帮助。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

您只需要包含其他条件即可。这可以处理多个分隔符。

我已将此更改Other:=False更新为Other:=True, OtherChar="="

Sub ImportTextFile()
    'Imports a text file
    Dim vFileName

    On Error GoTo ErrorHandle

     vFileName = Application.GetOpenFilename()

    'If the user pressed "Cancel" or didn't select a text file,
    'exit the procedure.
    If vFileName = False Then
       GoTo BeforeExit
    End If

    'Switch off screen updating for speed.
    Application.ScreenUpdating = False

    'We now import the selected text file, and data is
    'inserted in a new spreadsheet. If you want to use
    'another delimiter, you must change "Semicolon:=True"
    'to "Semicolon:=False" and set another delimiter
    '(e.g. "Tab") to True.
    Workbooks.OpenText fileName:=vFileName, _
        Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, _
        Comma:=False, Space:=False, Other:=True, OtherChar:="=", _
        TrailingMinusNumbers:=True, Local:=True

    'Just to show how we auto adjust the width of column A.
    Columns("A:A").EntireColumn.AutoFit

BeforeExit:
    Application.ScreenUpdating = True
    Exit Sub
ErrorHandle:
    MsgBox Err.Description
    Resume BeforeExit
End Sub