簡體   English   中英

作為工作表宏運行時,該子例程不起作用

[英]subroutine not working when run as a sheet macro

我有一個使用工作表宏(即工作表內部的而不在單獨的模塊中運行的宏)創建.xlsm文件的過程。

在一個工作表子例程中,我試圖使用此方法導入.csv文件:

With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;" & INFILE, Destination:=Range("$A$1"))
    .Name = "NLIST"
    .FieldNames = True
    .PreserveFormatting = True
    .RefreshStyle = xlInsertDeleteCells
    .SaveData = True
    .AdjustColumnWidth = True
    .TextFileStartRow = 1
    .TextFileParseType = xlFixedWidth
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileTabDelimiter = True
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
    .TextFileFixedColumnWidths = Array(8, 36, 2, 4, 7, 4, 4)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

問題是它不能作為工作表宏使用。 它只有在其自己的模塊中時才起作用。 我嘗試更改所有“。” 引用這種結構:

With sheets("NLIST").QueryTables.Add(Connection:= _
    "TEXT;" & INFILE, Destination:=Range("$A$1"))
    sheets("NLIST").Name = "NLIST"
    sheets("NLIST").FieldNames = True
End with

沒有布宜諾斯艾利斯

一如既往,任何幫助將不勝感激

Edit1:由於它不起作用,請嘗試在模塊級別創建過程,然后在工作表代碼中調用它。

例如: 這在模塊中

Sub AddConnection(targetWS As Worksheet, INFILE As String)

With targetWS
    With .QueryTables.Add(Connection:= _
        "TEXT;" & INFILE, Destination:=.Range("$A$1"))
        .Name = "NLIST"
        .FieldNames = True
        .PreserveFormatting = True
        .RefreshStyle = xlInsertDeleteCells
        .SaveData = True
        .AdjustColumnWidth = True
        .TextFileStartRow = 1
        .TextFileParseType = xlFixedWidth
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileTabDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileFixedColumnWidths = Array(8, 36, 2, 4, 7, 4, 4)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End With

End Sub

然后在工作表代碼中,您可以這樣稱呼它:

AddConnection Me, <FilePath> '/* if you are creating connection in that sheet */

要么

AddConnection Sheets("NLIST"), <FilePath> '/* creating it on another sheet */

未經測試,沒有辦法完成atm,但是我認為它應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM