首页 > 解决方案 > 如何在我的 VBA 代码中解决这个“下标超出范围错误”?

问题描述

我不断收到以下行的“下标超出范围”错误:Worksheets("Sheet3").Range("A4").Copy

我是 VBA 的新手,所以我确定我缺少一些东西 - 你有什么意见吗?

此代码的基础是将用户表单中的数据输入到一个工作表中,然后将该行代码复制到第一个空行中的另一个工作表中。

先感谢您!!

    Private Sub EnterButton_Click()
    
    Application.CutCopyMode = True
   'Determine emptyRow
    emptyrow = WorksheetFunction.CountA(Range("A:A")) + 1

    Sheet3.Activate

    'Transfer information
Cells(emptyrow, 1).Value = textbox1.Value
Cells(emptyrow, 2).Value = textbox2.Value
Cells(emptyrow, 3).Value = textbox3.Value
Cells(emptyrow, 4).Value = textbox4.Value
Cells(emptyrow, 5).Value = textbox5.Value
Cells(emptyrow, 6).Value = textbox6.Value
Cells(emptyrow, 7).Value = textbox7.Value
Cells(emptyrow, 8).Value = textbox8.Value
Cells(emptyrow, 9).Value = textbox9.Value
Cells(emptyrow, 11).Value = textbox11.Value
Cells(emptyrow, 12).Value = textbox12.Value
Cells(emptyrow, 13).Value = textbox13.Value
Cells(emptyrow, 14).Value = textbox14.Value
Cells(emptyrow, 17).Value = textbox17.Value
Cells(emptyrow, 18).Value = textbox18.Value
Cells(emptyrow, 19).Value = textbox19.Value
Cells(emptyrow, 20).Value = textbox20.Value
Cells(emptyrow, 21).Value = textbox21.Value
Cells(emptyrow, 25).Value = textbox25.Value
Cells(emptyrow, 26).Value = textbox26.Value
Cells(emptyrow, 27).Value = textbox27.Value
Cells(emptyrow, 28).Value = textbox28.Value
Cells(emptyrow, 29).Value = textbox29.Value
Cells(emptyrow, 33).Value = textbox33.Value
Cells(emptyrow, 34).Value = textbox34.Value
Cells(emptyrow, 35).Value = textbox35.Value
Cells(emptyrow, 36).Value = textbox36.Value
Cells(emptyrow, 37).Value = textbox37.Value
Cells(emptyrow, 41).Value = textbox41.Value
Cells(emptyrow, 42).Value = textbox42.Value
Cells(emptyrow, 43).Value = textbox43.Value
Cells(emptyrow, 44).Value = textbox44.Value
Cells(emptyrow, 45).Value = textbox45.Value
    
    Worksheets("Sheet3").Range("A4").Copy
    Worksheets("Sheet6").Range("A" & Rows.count_.End(xlUp).Row + 1).PasteSpecial Paste:=xlPasteFormulas

    Application.CutCopyMode = False

    End Sub

标签: excelvbauserformsubscript

解决方案


在您的 VBA 项目中,您很可能有类似Sheet3("Name that appear in Excel"). 它将解释为什么这条线有效:

Sheet3.Activate 

但不是这个。

Worksheets("Sheet3").Range("A4").Copy

如果您查看 VBA 中的 Sheet3 属性,您会发现您的 Sheet(Name)Sheet3,而您的 SheetName是不同的。第一个是 VBA 名称,第二个是出现在 Excel 工作簿上的名称。重命名选项卡时,您可以直接在 Excel 上更改第二个。

考虑到所有这些因素,这条线应该可以工作:

Sheet3.range("A4").copy

推荐阅读