繁体   English   中英

VBA文本导入和其他定界符“ =”

[英]VBA text import with other delimiter “=”

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

;

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

=

这使我出错。

对象“工作簿”的“打开文本”方法失败。

请找到附件我的示例文本文件,该文件通常具有扩展名.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

建议,想法对解决这个问题确实很有帮助。

先感谢您。

您只需要包括其他条件。 这可以处理多个定界符。

我已经更新了此更改,将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM