简体   繁体   中英

Opening an excel file & copying sheets using VBA

I need to copy a couple of excel sheets ("Y", "X") from one file to the same sheet in another excel file (call it Z - the same file that I'm using the VBA on). my limitation is that the name and path of the first excel file (with the X,Y) are changing, therefore I'm trying to write something more generic using the "as String" and the Application.GetOpenFilename() command but I'm receiving an error.

Tried to separate into 2 different subs

Sub BrowseForFile()
    Dim sFileName As String
    sFileName = Application.GetOpenFilename(, , "open the file: " )

    If sFileName = "false" Then Exit Sub
    MsgBox sFileName
    Workbooks.Open (sFileName)
    Workbooks(sFileName).Sheets("X").Activate
    Stop
  1. Runtime Error 9
  2. file doesn't find (1004 I think)

If the user presses the Cancel button then the GetOpenFilename function returns a boolean False not a string "false" so you need to test for If sFileName = False Then and declare it as Variant .

If you open a workbook always reference it to a variable so you can use that to access the workbook easily

Dim OpenedWb As Workbook
Set OpenedWb = Workbooks.Open(sFileName)

Then you can use the variable Wb to reference the workbook you opened

OpenedWb.Worksheets("X").Activate

Note that using .Select and .Activate is a bad practice and should be avoided ( How to avoid using Select in Excel VBA ). Instead use another reference to reference your workbook.

Dim ws As Worksheet
Set ws = OpenedWb.Worksheets("X")

And access a range like ws.Range("A1").Value for example.


Sub BrowseForFile()
    Dim sFileName As Variant 'needs to be variant because cancel returns a boolean False
    sFileName = Application.GetOpenFilename(, , "open the file: " )

    If sFileName = False Then Exit Sub

    MsgBox sFileName

    Dim OpenedWb As Workbook
    Set OpenedWb = Workbooks.Open(sFileName)

    Dim ws As Worksheet
    Set ws = OpenedWb.Worksheets("X")

    MsgBox ws.Range("A1").Value 'output the value of `A1` in worksheet `X` of workbook `sFileName`
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