Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Sub xlsurl()
- ' current workbook
- Dim wb As Workbook
- ' new worksheet to insert data
- Dim ws As Worksheet
- ' number of sheets in current workbook
- Dim i As Integer
- ' remote workbook
- Dim wurl As Workbook
- ' let's set some "constants"
- ' xls to download
- Const surl As String = _
- "https://www.ishares.com/uk/professional/en/products/251853/ishares-msci-brazil-ucits-etf-inc-fund/1535604580409.ajax?fileType=xls&fileName=iShares-MSCI-Brazil-UCITS-ETF-USD-Dist_fund&dataType=fund"
- ' list of sheets to import as a string with comas (no spaces!)
- Dim sheetsImport() As String
- sheetsImport = Split("Overview,Historical,Holdings", ",")
- ' obvious, i hope...
- Set wb = ThisWorkbook
- ' so let's open the remote xls
- Set wurl = Workbooks.Open(surl)
- ' ok, now we will loop through all names in sheetImport; it could be only 1 of course
- ' attention: no error handling! so if no sheet exists, etc - the code will crash
- ' ---start of sheets loop---
- Dim tmpsheet As Variant
- For Each tmpsheet In sheetsImport
- ' counting sheets in current workbook; this is a safe solution - you can always change it to replace data in the existing sheet
- i = wb.Sheets.Count
- ' add new sheet at the end of existing ones
- Set ws = wb.Sheets.Add(After:=wb.Sheets(i))
- ' new sheet name is set to the name of the imported sheet + underscore + current date
- ' safety feature for sheet name:
- ' if sheet with that name already exists - add _I to the date until free name is found
- ' for example:
- ' original_sheetname_2021-01-06 exists
- ' original_sheetname_2021-01-06_1 is created; if exists
- ' original_sheetname_2021-01-06_2 is created; and so on
- Dim nameDate As String
- Dim nameI As Integer
- nameDate = tmpsheet & "_" & Date
- nameI = 0
- Dim f As Boolean
- f = WsExists(nameDate)
- Do While f
- nameI = nameI + 1
- nameDate = tmpsheet & "_" & Date & "_" & nameI
- f = WsExists(nameDate)
- Loop
- ' end of safe name loop
- ' set new sheet safe name
- ws.Name = nameDate
- ' just for easy reference
- Dim wsheet As Worksheet
- ' set it to the selected sheet from the downloaded XLS
- Set wsheet = wurl.Worksheets(tmpsheet)
- ' and copy its data to the new sheet in the current workbook
- wsheet.Cells.Copy Destination:=ws.Range("A1")
- Next tmpsheet
- ' ---end of sheets loop---
- ' close downloaded file
- wurl.Close
- End Sub
- Function WsExists(sh As String, Optional wb As Workbook) As Boolean
- Dim shtout As Worksheet
- If wb Is Nothing Then Set wb = ThisWorkbook
- On Error Resume Next
- Set shtout = wb.Sheets(sh)
- On Error GoTo 0
- WsExists = Not shtout Is Nothing
- End Function
Advertisement
Add Comment
Please, Sign In to add comment