简体   繁体   English

VBA:下标超出范围

[英]VBA: Subscript out of range

similar questions have been asked but I think I have a different problem: 有人问过类似的问题,但我想我有一个不同的问题:

 Workbooks.Open Filename:=filepath & "PLT.xlsx"

Worksheets("Sheet1").Range(Worksheets("Sheet1").Range("A1:B1"), Worksheets("Sheet1").Range("A1:B1").End(xlDown)).Copy
Windows("XXX.xslm").Activate
w1.Range("A4").PasteSpecial Paste:=xlPasteValues

The second line is the problem. 第二行是问题。 In fact, it does not copy the cells I want. 实际上,它不会复制我想要的单元格。 When I open that workbook, the whole worksheet is selected. 当我打开该工作簿时,将选择整个工作表。

I do not understand why I get that error. 我不明白为什么会收到该错误。

Yikes. 让人惊讶。 If you want to copy values to it the easy way: 如果要将值复制到它的简单方法:

Global fso As New FileSystemObject

Public Sub CopyValuesTest()

    ' Get references to the files
    Dim wb1 As Workbook, wb2 As Workbook
    Set wb1 = Workbooks.Open(fso.BuildPath(filepath, "PLT.xlsx"))
    Set wb2 = Workbooks("XXX")

    ' Get references to the sheets
    Dim ws1 As Worksheet, ws2 As Worksheet
    Set ws1 = wb1.Sheets("Sheet1")
    Set ws2 = wb2.Sheets("Sheet1")

    ' Count non-empty rows under A1. Use 2 columns
    Dim N As Integer, M As Integer
    N = CountRows(ws1.Range("A1")): M = 2

    ' This copies the values
    ws2.Range("A4").Resize(N, M).Value = ws1.Range("A1").Resize(N, M).Value
End Sub

Public Function CountRows(ByRef r As Range) As Long
    If IsEmpty(r) Then
        CountRows = 0
    ElseIf IsEmpty(r.Offset(1, 0)) Then
        CountRows = 1
    Else
        CountRows = r.Worksheet.Range(r, r.End(xlDown)).Rows.Count
    End If
End Function

And make sure your filepath is defined. 并确保定义了文件filepath Also to use FileSystemObject see https://stackoverflow.com/a/5798392/380384 有关使用FileSystemObject请参见https://stackoverflow.com/a/5798392/380384

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM