我想将数据从CSV文件复制到Excel工作表中。有11个.csv文件。到目前为止,我有这个(它是先前文章的修改版本):

Sub importData()
  Dim filenum(0 To 10) As Long
  filenum(0) = 052
  filenum(1) = 060
  filenum(2) = 064
  filenum(3) = 068
  filenum(4) = 070
  filenum(5) = 072
  filenum(6) = 074
  filenum(7) = 076
  filenum(8) = 178
  filenum(9) = 180
  filenum(10) = 182

  Dim sh1 As Worksheet
  On Error GoTo my_handler

  For lngPosition = LBound(filenum) To UBound(filenum)
    'Windows(filenum(lngPosition) & ".csv").Activate
    Workbooks.Add(filenum(lngPosition) & ".csv").Activate
Range("A1").Select
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
    Selection.Copy
    Windows("30_graphs_w_Macro.xlsm").Activate
    Set sh1 = Worksheets(filenum(lngPosition)).Activate
    Range("A69").Paste
    Range("A69").Select

  Next lngPositionlngPositionlngPosition

my_handler:
  MsgBox "All done."
  Exit Sub
End Sub


这段代码为我提供了下标超出范围错误的代码:

Set sh1 = Worksheets(filenum(lngPosition)).Activate

最佳答案

设置sh1 = Worksheets(filenum(lngPosition))。


您收到Subscript out of range error错误,因为它找不到该工作表。

也请...请...请不要使用.Select/.Activate/Selection/ActiveCell您可能想查看How to Avoid using Select in Excel VBA Macros

09-09 19:06