繁体   English   中英

使用 InputBox 复制粘贴整个工作表

[英]Copy paste entire worksheet with InputBox

我有这个代码,我正在尝试做一个简单的任务,这对我来说显然不是那么简单。 我想对 vba 说要复制哪个工作表(这里是 InputBox 的功能,我在其中插入工作表名称),然后,如果存在(即如果名称正确),则在工作表 20 中执行复制粘贴,如果没有存在,去exitmysub。

现在,我有两个问题:

1)它不复制粘贴。 或者至少,并非总是如此。 有时是,有时不是。 而且我真的不明白为什么(我总是输入正确的工作表名称)

2)即使名称正确,代码也会运行msgbox(“无效的工作表名称”)。 虽然我希望它仅在我放置的工作表名称不存在时触发。

谢谢你的帮助!

Option Explicit

Dim text As String, ws As Worksheet


Sub copyentiresheet()

text = InputBox("Write here the Local Deposit Sheet you want to update", "Update Local Deposit Monitoring")

On Error GoTo exitmysub
Sheet20.Cells.Clear
Set ws = Sheets(text)
    ws.Cells.Copy

Sheets20.Paste


exitmysub:
MsgBox ("Invalid Sheet Name")

End Sub

尝试这个...

Option Explicit

Dim text As String, ws As Worksheet

Sub copyentiresheet()

text = InputBox("Write here the Local Deposit Sheet you want to update", "Update Local Deposit Monitoring")

On Error GoTo ErrorMySub
Sheet20.Cells.Clear
Set ws = Sheets(text)
ws.Cells.Copy Sheet20.Range("A1")

ExitMySub:
Exit Sub

ErrorMySub:
MsgBox ("Invalid Sheet Name")

End Sub

复印整张纸

强调

  • InputBox VBA 帮助:如果用户单击取消,该函数将返回一个长度为零的字符串 ( "" )。
  • 如果工作表的CodeName错误,代码将无法编译。 不需要错误处理。
  • 使用With语句避免声明不必要的对象引用。
  • 使用CodeName.Parent参考工作簿,以避免在ActiveWorkbookThisWorkbook或按名称工作簿之间进行选择时ActiveWorkbook
  • 在错误处理程序之前(之间) Exit Sub

编码

Option Explicit

Sub CopyEntireSheet()

  Dim text As String

  text = InputBox("Write here the Local Deposit Sheet you want to update", _
      "Update Local Deposit Monitoring")

  If text = "" Then Exit Sub ' If the user clicks Cancel.

  Sheet20.Cells.Clear ' If sheet's code name is wrong, code won't compile.

  On Error GoTo SourceSheetErr

  With Sheet20.Parent.Worksheets(text)

    On Error GoTo RangeErr
    .Cells.Copy Sheet20.Cells

  End With

Exit Sub

SourceSheetErr:
  MsgBox "Invalid Source Sheet Name."
Exit Sub

RangeErr:
  MsgBox "(Copy) Range Error."

End Sub

暂无
暂无

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

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