Excel VBA更改连接路径但保留分隔符和列格式

时间:2017-06-15 17:19:48

标签: excel vba csv

我有一个excel文件,其中包含一个与文本文件的连接。我需要每天更新此文件的路径(因为文件名因我无法控制的原因而更改)。我使用以下代码来改变路径,它工作得很好。问题是我丢失了所有其他选项,例如分隔符分隔以及列数据类型。

有没有办法可以改变路径并保持格式化?

以下是代码:

Sub Update_Connection()

        Dim Conn As Variant
        Dim ConString As String
        Dim oldPath As String, NewPath As String

        NewPath = "\\Reports\Data\dailydata" & (Application.WorksheetFunction.Concat(Format(Now(), "dd"), Format(Now(), "mm"), Format(Now(), "yy")) * 4) & ".txt"
        Debug.Print NewPath

        Set Conn = ActiveWorkbook.Connections.Item(1)

        'Debug.Print Conn.TextConnection.Connection

        ConString = Conn.TextConnection.Connection

        oldPath = Split(ConString, ";")(1)

        ConString = Replace(ConString, oldPath, NewPath)

       Conn.TextConnection.Connection = ConString

    End Sub

1 个答案:

答案 0 :(得分:0)

这可能不是您特定问题的答案,但我会使用一种方法,我可以始终完全控制发生的事情,而不是让Excel照顾您,因为它可能因版本而异。您可以控制和更改许多属性。我会在您拥有的工作簿中插入一个形状,右键单击它并分配RunClick子。每次你想从文本文件中提取数据时,你只需要点击它,一切都应该没问题。唯一的一部分是你必须更多地开发它,所以捕获最新文本文件的全名,这样你就不会手动做任何事情,而且你的数据是完整导入的。

Sub RunClick()
    Dim str As String
    str = "T:\MyFolder\ABC.txt"
    Call CreateConnectionToTextFile(str)
End Sub

Sub CreateConnectionToTextFile(sTextFileFullName As String)
    On Error GoTo ErrorHandler
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & sTextFileFullName, Destination:=Range("$A$1"))
        .Name = "MAKT"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 1252
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1) 'we have 3 columns that were imported, and all of them are general 1=general text =2 and so on
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

    MsgBox "Now Connected Successfully.", vbInformation, "Success"

    Exit Sub

的ErrorHandler:         如果Err.Number<> 0然后             MsgBox“无法建立连接。”,vbCritical,“错误”         万一     结束子