Search code examples
excelvbaweb-scrapingfilesystemobject

Can't save and close a newly created workbook in a customized folder


I've create a macro which is able to parse some movie names from a torrent site.

What I want to do now is (My script can satisfy the first three requirements already except the fourth one):

1. Create a folder in my desktop
2. Create a new workbook after the name of the `Genre`
3. write the data in that new workbook
4. Save and close the data-ridden workbook in the newly created folder

This is my try so far:

Sub CreateAndSaveWorbook()
    Const link = "https://yts.am/browse-movies/0/all/action/0/latest"
    Dim Http As New XMLHTTP60, Html As New HTMLDocument, genre$
    Dim post As HTMLDivElement, wb As Workbook
    Dim daddr$, fdObj As Object

    daddr = Environ("USERPROFILE") & "\Desktop\Test\"
    Set fdObj = CreateObject("Scripting.FileSystemObject")
    If Not fdObj.FolderExists(daddr) Then fdObj.CreateFolder (daddr)

    With Http
        .Open "GET", link, False
        .send
        Html.body.innerHTML = .responseText
    End With

    genre = Html.querySelector("select[name='genre'] option[value='action']").innerText
    Set wb = Workbooks.Add
    wb.SaveAs daddr & genre & ".xlsx"

    For Each post In Html.getElementsByClassName("browse-movie-bottom")
        R = R + 1: wb.Sheets(1).Cells(R, 1) = post.getElementsByClassName("browse-movie-title")(0).innerText
    Next post
End Sub

How can I save and close a newly created workbook in a customized folder?


Solution

  • Here's your answer :) :Change wb.saveAs to wb.Close true, daddr & genre & ".xlsx"