【问题标题】:VBA: Copy range. run time error 9 - subscript out of rangeVBA:复制范围。运行时错误 9 - 下标超出范围
【发布时间】:2017-08-25 23:13:29
【问题描述】:

我是 VBA 新手。我正在尝试将列从一个工作簿复制到另一个工作簿。下面是我尝试使用的 sub,但出现“运行时错误 9 - 下标超出范围”的错误。有什么建议吗?

Sub copydata(wbSource As String, wsSource As String, rangeSource As String, wbDest As String, wsDest As String, rangeDest As String)
    Workbooks(wbSource).Worksheets(wsSource).Range(rangeSource).copy Destination:=Workbooks(wbDest).Worksheets(wsDest).Range(rangeDest)
End Sub

Sub result()
    ' I also tried to set wsSource and wsDest to 1 but still doesn't work
    Call copydata("es.csv", "es", "A:B", "Workbook1.xlsm", "result", "A:B")
End Sub

谢谢

编辑: 它们在同一个目录中。我在 Workbook1.xlsm 中创建模块

【问题讨论】:

  • 其中一个工作簿/工作表不存在。
  • 请检查编辑
  • 它们“在同一个文件夹中”是不够的。它们必须在同一个工作区中,才能在不使用完全限定的外部引用的情况下从另一个工作簿(例如 .csv)引用。

标签: excel vba copy runtime-error


【解决方案1】:

复制时它们必须都是打开的,它们都在同一个文件夹中没有关系。

你应该打开它们,然后你可以复制数据。

检查两个工作表名称(es 为 es.csv,结果为 Workbook1.xslm)

Sub copydata(wbSource As String, wsSource As String, rangeSource As String, 
wbDest As String, wsDest As String, rangeDest As String)
    Workbooks(wbSource).Worksheets(wsSource).Range(rangeSource).Copy 
Destination:=Workbooks(wbDest).Worksheets(wsDest).Range(rangeDest)
End Sub

Sub result()
    ' I also tried to set wsSource and wsDest to 1 but still doesn't work
    If Not IsWorkbookOpen("es.csv") Then OpenWorkbook ("es.csv")
    End If
    Call copydata("es.csv", "es", "A:B", "Workbook1.xlsm", "result", "A:B")
End Sub

Sub OpenWorkbook(fileName As String)
    Dim activePath As String
    activePath = Application.ActiveWorkbook.Path
    Application.Workbooks.Open (activePath & Application.PathSeparator & 
fileName)
End Sub

Private Function IsWorkbookOpen(wbName As String) As Boolean
    Dim wb As Workbook

    On Error GoTo Handler
    Set wb = Workbooks(wbName)
    If wb.Name = wbName Then
        Set wb = Nothing
        IsWorkbookOpen = True
    Else
Handler:
        IsWorkbookOpen = False
    End If
End Function

【讨论】:

  • 哦,是的。我不知道我需要先打开所有文件。无论如何,有什么功能可以在不打开所有文件的情况下进行复制吗?
  • 如果是csv文件可以使用ActiveWorkbook.Queries方法msdn.microsoft.com/en-us/vba/excel-vba/articles/…
猜你喜欢
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
相关资源
最近更新 更多