Excel VBA超出范围

问题描述 投票:1回答:1

我找到了这个代码,我试图改变它,以便导入的数据存储在另一个工作表中。

第一个代码是Destination:=ActiveCell,我试图改变它,所以数据存储在另一张表中。我也尝试过这个:Destination:=Workbook.Sheets(CSV).Cells(1, 1))但它也不起作用。

我也在寻找代码来自动选择名为export-price的最新csv文件,但我还没有找到解决方案。

Sub LoadProducts()
    Dim fileName As String, folder As String

    folder = "C:\Users\CP\Downloads\"
    fileName = ActiveCell.Value

    ActiveCell.Offset(1, 0).Range("A1").Select


    With ActiveSheet.QueryTables _
        .Add(Connection:="TEXT;" & folder & fileName, Destination:=Workbook.Sheets(CSV).Cells(1, 1))
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 850
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = True
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub
excel vba csv excel-vba
1个回答
2
投票

您需要正确声明对象然后使用它们。这是一个例子。适用时更改。

Dim wb As Workbook, thiswb As Workbook
Dim ws As Worksheet, thisws As Worksheet

'~~> Change as applicable
Set thiswb = ThisWorkbook
Set thisws = thiswb.Sheets("Sheet1")

CSV = "Sheet1"
Set wb = Workbooks.Open("C:\Blah Blah.xlsx")
Set ws = wb.Sheets(CSV)

With thisws.QueryTables _
    .Add(Connection:="TEXT;" & folder & Filename, Destination:=ws.Cells(1, 1))
© www.soinside.com 2019 - 2024. All rights reserved.