简体   繁体   中英

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.

Now, I have two problems:

1) It does not copy paste. 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"). 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

Copy Entire Sheet

Highlights

  • InputBox VBA Help: If the user clicks Cancel, the function returns a zero-length string ( "" ).
  • If the sheet's CodeName is wrong, the code won't compile. No error handling necessary.
  • Use the With Statement to avoid declaring unnecessary object references.
  • Refer to a workbook using CodeName.Parent to avoid wrecking yourself about choosing between ActiveWorkbook , ThisWorkbook or workbook by name.
  • Exit Sub before (in between) error handlers.

The Code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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