【问题标题】:Getting Excel Vba Runtime Error 1004获取 Excel Vba 运行时错误 1004
【发布时间】:2018-03-15 13:11:10
【问题描述】:
Private Sub CommandButton3_Click()
    Dim rownum, startcol, endcol, holder As Integer
    rownum = InputBox("Enter the row that swapping process going to happen")
    startcol = InputBox("Enter the column of the cell you want to swap")
    endcol = InputBox("Enter the column of the cell that you wanted swap with")
    holder = Cells(rownum, startcol).Value
    Cells(rownum, startcol).Value = Cells(rownum, endcol).Value
    Cells(rownum, endcol).Value = holder
End Sub

运行时错误 1004 - “运行时错误‘1004’: 应用程序定义或对象定义的错误”

似乎无法理解。

【问题讨论】:

  • 我看到的第一件事是您的 DIM 语句需要清理...只有 holder 设置为整数,其他一切都是变体。其次,您可能不希望 rownum 成为整数,因为您很容易在大型电子表格中达到其限制。
  • 您还需要将父工作表分配给每个范围对象:Worksheets("Sheet1").Cells(...
  • 由于您没有正确地Dim 变量,我猜问题是rownum 等改为填充String。修复变量,剩下的就OK了
  • 非常感谢,这么简单的错误。我没有意识到它们是变体。
  • 根据您的最后一个问题,我建议以“我如何……”或“如何……”的形式提出问题。 “请帮助我”的形式在这里通常被理解为“为我做我的工作”,即使这不是你想要的。

标签: vba excel


【解决方案1】:

正确调暗变量并使用 application.inputbox 获得更多选项。

'using column numbers
Private Sub CommandButton3_Click()
    Dim rownum as long, startcol as long, endcol as long, holder As variant
    rownum = application.InputBox("Enter the row that swapping process going to happen", type:=1)
    startcol = application.InputBox("Enter the column number of the cell you want to swap", type:=1)
    endcol = application.InputBox("Enter the column numbedr of the cell that you wanted swap with", type:=1)
    holder = Cells(rownum, startcol).Value
    Cells(rownum, startcol).Value = Cells(rownum, endcol).Value
    Cells(rownum, endcol).Value = holder
End Sub

'using column letters
Private Sub CommandButton3_Click()
    Dim rownum as long, startcol as string, endcol as string, holder As variant
    rownum = application.InputBox("Enter the row that swapping process going to happen", type:=1)
    startcol = application.InputBox("Enter the column letter of the cell you want to swap", type:=2)
    endcol = application.InputBox("Enter the column letter of the cell that you wanted swap with", type:=2)
    holder = Cells(rownum, startcol).Value
    Cells(rownum, startcol).Value = Cells(rownum, endcol).Value
    Cells(rownum, endcol).Value = holder
End Sub

type:=1 告诉 application.inputbox 期待一个数字; type:=2 告诉 application.inputbox 期待一个字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多