简体   繁体   中英

How to activate opened excel in VBA

I have a VBA code that I used to open an excel and do an automatic process. My code is

Dim strPath As String
Dim intChoice As Integer
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)

Workbooks.Open Filename:= _
    strPath

The process is done here, and this process is navigating between 2 excels, the one that contains the Macro and the one that contains the data. Let's say Excel A and Excel B. I do the automation in Excel B based on a button in Excel A and then I cut the data from B and add it to A. Now my problem is that the excels which contains the data are different in names, so I reach to this point in the code:

Windows("EPS.xlsx"). _
    Activate

Where I want this "EPS.xlsx" to be replaced by file which was already opened by strPath in the code I wrote in the beginning of this question.

Thank you in advance

Don't think about activating or selecting any workbooks. All you want to do is reference the correct workbook.

Rather than use Workbooks.Open Filename:= strPath which will just open the file, you want to open the file and store a reference to it in a variable. You can then use that variable whenever you want to do something with the workbook.

Sub Test()

    Dim wrkBk1 As Workbook
    Dim wrkBk2 As Workbook

    Set wrkBk1 = Workbooks.Open(Filename:=strPath)
    Set wrkBk2 = Workbooks.Open(Filename:=strOtherPath)

    wrkBk1.Worksheets("Sheet1").Range("A1") = 5
    wrkBk2.Worksheets("Sheet1").Range("A1") = wrkBk1.Worksheets("Sheet1").Range("A1")

    wrkBk1.Worksheets("Sheet2").Range("A2").NumberFormat = "@"
    wrkBk2.Worksheets("Sheet1").Range("A5").Font.Color = RGB(255, 0, 0)

End Sub  

Your code would look something like:

Sub Test2()

    Dim strPath As String
    Dim intChoice As Integer

    Dim wrkBk As Workbook

    intChoice = Application.FileDialog(msoFileDialogOpen).Show
    If intChoice <> 0 Then
        strPath = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)

        Set wrkBk = Workbooks.Open(Filename:=strPath)
        MsgBox wrkBk.Name & " has been opened.", vbOKOnly + vbInformation
    End If

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