'Importing Data from a Password Protected Website

I've the following macros working independently of each other (sort of). I need them working together.

First I import data from a URL that points to a CSV file (php script calling on a SQL query). It imports the data from the CSV into Excel.

Sub Import_Data()
  
Dim originalWB As Workbook
Dim secondWB As Workbook
Set originalWB = ActiveWorkbook

Workbooks.Open Filename:="http://example.com/test.php"

Set secondWB = ActiveWorkbook

Range("A1:Z100").Select
Selection.Copy
        
originalWB.Activate
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
  xlNone, SkipBlanks:=False, Transpose:=False
        
secondWB.Close
        
End Sub

I thought I should add a level of security to the original URL (http://example.com/test.php) so I added my session login to the page.

<?php
session_start();
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
    header('Location: index.php');
    exit();
}
?>

As expected, when I run the original Import_Data macro, I get data from the index.php page, rather than the CSV at the original URL.

To overcome this, I thought I could login with another macro before running the Import_Data macro.
This doesn't work in the sense of helping me with my Import_Data macro. It logs me in, but I'm assuming that the Import_Data macro is not using a browser, so my browser based approach below isn't helping.

How can I can run the VBA

Workbooks.Open Filename:="http://example.com/test.php"

when that page is password protected (requiring an active session)?

Sub login()

    Const Url$ = "http://example.com"

    Dim UserName As String, Password As String, LoginData As Worksheet
    Set LoginData = ThisWorkbook.Worksheets("Sheet1")
    UserName = LoginData.Cells(1, "B").Value
    Password = LoginData.Cells(2, "B").Value

    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    With ie

        .navigate Url
        ieBusy ie
        .Visible = True

        Dim oLogin As Object, oPassword As Object
        Set oLogin = .document.getElementsByName("fac_id")(0)
        Set oPassword = .document.getElementsByName("password")(0)

        oLogin.Value = UserName
        oPassword.Value = Password
        .document.forms(0).submit

    End With

End Sub

Sub ieBusy(ie As Object)
    Do While ie.Busy Or ie.readyState < 4
        DoEvents
    Loop
End Sub


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source