[英]Copy paste entire worksheet with InputBox
I have this code and I am trying to do a simple task, which apparently it is not so simple to me.我有这个代码,我正在尝试做一个简单的任务,这对我来说显然不是那么简单。 I want to say to vba which sheet to copy (here the functionality of the InputBox, where I insert the sheet name) and then, if exists (ie if the name is correct) perform the copy paste in the sheet20, if it does not exist, go to exitmysub.
我想对 vba 说要复制哪个工作表(这里是 InputBox 的功能,我在其中插入工作表名称),然后,如果存在(即如果名称正确),则在工作表 20 中执行复制粘贴,如果没有存在,去exitmysub。
Now, I have two problems:现在,我有两个问题:
1) It does not copy paste. 1)它不复制粘贴。 Or at least, not always.
或者至少,并非总是如此。 Sometimes yes, sometimes not.
有时是,有时不是。 And I really dont understand why (I always put the correct sheet names)
而且我真的不明白为什么(我总是输入正确的工作表名称)
2) Even if the name is correct, the code runs the msgbox ("Invalid Sheet Name"). 2)即使名称正确,代码也会运行msgbox(“无效的工作表名称”)。 While I wantthat it triggers only if the sheet name I put does not exist.
虽然我希望它仅在我放置的工作表名称不存在时触发。
Thank you for you help!谢谢你的帮助!
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
Try this...尝试这个...
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 Help: If the user clicks Cancel, the function returns a zero-length string (
""
).InputBox VBA 帮助:如果用户单击取消,该函数将返回一个长度为零的字符串 (
""
)。- If the sheet's CodeName is wrong, the code won't compile.
如果工作表的CodeName错误,代码将无法编译。 No error handling necessary.
不需要错误处理。
- Use the
With
Statement to avoid declaring unnecessary object references.使用
With
语句避免声明不必要的对象引用。- Refer to a workbook using
CodeName.Parent
to avoid wrecking yourself about choosing betweenActiveWorkbook
,ThisWorkbook
or workbook by name.使用
CodeName.Parent
参考工作簿,以避免在ActiveWorkbook
、ThisWorkbook
或按名称工作簿之间进行选择时ActiveWorkbook
。Exit Sub
before (in between) error handlers.在错误处理程序之前(之间)
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.