Excel VBA超出范围

我发现这个代码,我试图改变它,所以导入的数据存储在另一个工作表。

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

我也在寻找代码来自动select名称为export-price的最新csv文件,但我还没有find一个解决scheme呢。

 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 

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

 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))