Consulting

Results 1 to 2 of 2

Thread: Solved: Clear sheet only if File is selected

  1. #1
    VBAX Mentor
    Joined
    Jan 2009
    Posts
    304
    Location

    Solved: Clear sheet only if File is selected

    I have a workbook with several worksheets that the user can update using some buttons.

    I use the VBA below to provide the user with the option of updating the worksheets.

    This work fine.

    I clear the contains of the destination worksheet early in the routine.

    I was wondering if this could be modified so that the orginal worksheet (Sheet21 in this example) only gets cleared if the user actually selects a source file with the DialogBox.

    If no file is selected then the original data is still intact.

    Can this be done?

    Thanks...

    JimS

    [vba]
    Sub Import_File1()

    Dim DestBook As Workbook, SourceBook As Workbook
    Dim DestCell As Range
    Dim RetVal As Boolean

    ' Turn off screen updating.
    Application.ScreenUpdating = False

    ' Unhide and select destination sheet
    Sheet21.Visible = True
    Sheet21.Select

    ' Added to clear Sheet before Import
    Cells.Select
    Selection.ClearContents
    Range("A1").Select

    ' Set object variables for the active book and active cell.
    Set DestBook = ActiveWorkbook
    Set DestCell = ActiveCell

    ' Show the Open dialog box.
    RetVal = Application.Dialogs(xlDialogOpen).Show("*.*")

    ' If Retval is false (Open dialog canceled), exit the procedure.
    If RetVal = False Then Exit Sub

    ' Set an object variable for the workbook containing the text file.
    Set SourceBook = ActiveWorkbook

    ' Copy the contents of the entire sheet containing the text file.
    Range(Range("A1"), Range("A1").SpecialCells(xlLastCell)).Copy

    ' Activate the destination workbook and paste special the values from the text file.
    DestBook.Activate
    Sheet21.Select
    DestCell.PasteSpecial Paste:=xlPasteFormats
    DestCell.PasteSpecial Paste:=xlValues

    ' Close the book containing the text file.
    Application.DisplayAlerts = False
    SourceBook.Close False
    Application.DisplayAlerts = True

    End Sub
    [/vba]

  2. #2
    Moderator VBAX Master austenr's Avatar
    Joined
    Sep 2004
    Location
    Maine
    Posts
    2,033
    Location
    try defining a string variable, then right after the dialogue box if a file is selected, set the string variable to true and if so clear the sheet otherwise error out.
    Peace of mind is found in some of the strangest places.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •