Need to restructure data received from web into excel - vba

I have a excel macro that searches many values in a column and puts the data into another worksheet. However the data is scattered and need to arrange it.
Here is the macro im using
Sub Search()
Dim i As Integer, n As Integer, SearchString As String, ws As Worksheet, ws2 As Worksheet
Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String
strPrompt = "Hit OK when you wish to proceed to the next search item."
strTitle = "Next Search"
Set ws = Sheets("FINAL")
Set ws2 = Sheets("AllData")
n = ws.Range("C2").End(xlDown).Row
For i = 2 To n
SearchString = ws.Cells(i, 3).Value
With Worksheets("Query").QueryTables.Add(Connection:= _
"URL;https://www.*****.com/catalog/***.hsm?ItemNumber=" & SearchString _
, Destination:=Worksheets("Query").Range("A1"))
.Name = SearchString
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebTables = "1"
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
iRet = MsgBox(strPrompt, vbYesNo, strTitle)
If iRet = vbNo Then
End
Else
End If
Next i
End Sub
Here is how the data is being set in my sheet
I would like to have anything that starts with the following put in columns
Crosses To:
Replaces:
Crossed From:
Also, I have my .Name set to my searchString and .FieldNames set to true but they are not showing up.
The end result i would like to have is this
+---------------+--------------+--------------+--------------+
- SearchString - Sub - Sub - Sub -
+---------------+--------------+--------------+--------------+
- AR34567 - A-TY25993 - - -
- AR11160 - TS-1087 - AR11300 - D2-0099N -
+---------------+--------------+--------------+--------------+
There would be more sub column's for AR11160, just put a few in the table above to give you the idea what i want.
UPDATE
I was able to start tweaking the data as I need it. However, I can only seem to get the number i need on the same row. On the image above you see that column K has many numbers under Crossed From:. So I need to bring all those numbers too.
Please help
Sub Search2()
Dim i As Integer, n As Integer, SearchString As String
Dim shFinal As Worksheet, shQuery As Worksheet, shAllData As Worksheet
Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String
Dim m As Long, p As Long, q As Long, r As Long
Dim vSrc As Variant, vDest() As Variant
Dim r1 As Range
Dim Blank As String
strPrompt = "Hit OK when you wish to proceed to the next search item."
strTitle = "Next Search"
Set shFinal = Sheets("FINAL")
Set shQuery = Sheets("Query")
Set shAllData = Sheets("AllData")
n = shFinal.Range("C2").End(xlDown).Row
q = 1
For i = 2 To n
SearchString = shFinal.Cells(i, 3).Value
Set qt = shQuery.QueryTables.Add(Connection:= _
"URL;https://www.***.com/catalog/***.hsm?ItemNumber=" & SearchString _
, Destination:=Worksheets("Query").Range("A1"))
With qt
.Name = SearchString
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebTables = "1"
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
shAllData.Cells(q, 1) = SearchString
p = 1
Do While p < 30
If shQuery.Cells(p, 4) Like "Replaces:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
If shQuery.Cells(p, 4) Like "Crossed From:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
If shQuery.Cells(p, 4) Like "Crosses To:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
p = p + 1
Loop
iRet = MsgBox(strPrompt, vbYesNo, strTitle)
If iRet = vbNo Then
End
Else
shQuery.UsedRange.ClearContents
End If
q = q + 1
Next i
End Sub
ANOTHER UPDATE
Another Update
I know have the data being placed like i want it. Just have one issue. When a value is searched and not found i get a error on this line [.Refresh BackgroundQuery:=False]
How can i tell this code if a result is not returned skip it?
Sub Search2()
Dim i As Integer, n As Integer, SearchString As String
Dim shFinal As Worksheet, shQuery As Worksheet, shAllData As Worksheet
Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String
Dim m As Long, p As Long, q As Long, r As Long, s As Long
Dim range As range
Dim vSrc As Variant, vDest() As Variant
Dim r1 As range
strPrompt = "Hit OK when you wish to proceed to the next search item."
strTitle = "Next Search"
Set shFinal = Sheets("FINAL")
Set shQuery = Sheets("Query")
Set shAllData = Sheets("AllData")
n = shFinal.range("C2").End(xlDown).Row
q = 1
For i = 2 To n
SearchString = shFinal.Cells(i, 3).Value
Set qt = shQuery.QueryTables.Add(Connection:= _
"URL;https://www.***.com/catalog/***.hsm?ItemNumber=" & SearchString _
, Destination:=Worksheets("Query").range("A1"))
With qt
.Name = SearchString
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebTables = "1"
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
shAllData.Cells(q, 1) = SearchString
p = 1
Do While p < 30
If shQuery.Cells(p, 4) Like "Replaces:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
If shQuery.Cells(p, 4) Like "Crossed From:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
If shQuery.Cells(p, 4) Like "Crosses To:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
Set range = shQuery.range("E2:E25")
For Each cell In range
If IsEmpty(cell) Then
Exit For
Else
r = p + 1
shAllData.Cells(q, r) = shQuery.Cells(r, 5)
End If
Next
p = p + 1
Loop
iRet = MsgBox(strPrompt, vbYesNo, strTitle)
If iRet = vbNo Then
shQuery.UsedRange.ClearContents
End
Else
shQuery.UsedRange.ClearContents
End If
q = q + 1
Next i
End Sub

To answer your latest updated question
I know have the data being placed like i want it. Just have one issue. When a value is searched and not found i get a error on this line [.Refresh BackgroundQuery:=False]
How can i tell this code if a result is not returned skip it?
Below is your complete code with an error handler.
I added an On Error Resume Next statement before the line .Refresh BackgroundQuery.
After that, it checks if an error has occurred:
If not it executes your code, like it does now.
If yes, then it skips your code, resets the error handler, and goes to the next i.
Sub Search2()
Dim i As Integer, n As Integer, SearchString As String
Dim shFinal As Worksheet, shQuery As Worksheet, shAllData As Worksheet
Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String
Dim m As Long, p As Long, q As Long, r As Long, s As Long
Dim range As range
Dim vSrc As Variant, vDest() As Variant
Dim r1 As range
strPrompt = "Hit OK when you wish to proceed to the next search item."
strTitle = "Next Search"
Set shFinal = Sheets("FINAL")
Set shQuery = Sheets("Query")
Set shAllData = Sheets("AllData")
n = shFinal.range("C2").End(xlDown).Row
q = 1
For i = 2 To n
SearchString = shFinal.Cells(i, 3).Value
Set qt = shQuery.QueryTables.Add(Connection:= _
"URL;https://www.***.com/catalog/***.hsm?ItemNumber=" & SearchString _
, Destination:=Worksheets("Query").range("A1"))
With qt
.Name = SearchString
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebTables = "1"
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
On Error Resume Next '<-- Added line
.Refresh BackgroundQuery:=False
End With
If Err = 0 Then '<-- Added line
On Error Goto 0 '<-- Added line
shAllData.Cells(q, 1) = SearchString
p = 1
Do While p < 30
If shQuery.Cells(p, 4) Like "Replaces:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
If shQuery.Cells(p, 4) Like "Crossed From:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
If shQuery.Cells(p, 4) Like "Crosses To:*" Then shAllData.Cells(q, p) = shQuery.Cells(p, 5)
Set range = shQuery.range("E2:E25")
For Each cell In range
If IsEmpty(cell) Then
Exit For
Else
r = p + 1
shAllData.Cells(q, r) = shQuery.Cells(r, 5)
End If
Next
p = p + 1
Loop
iRet = MsgBox(strPrompt, vbYesNo, strTitle)
If iRet = vbNo Then
shQuery.UsedRange.ClearContents
End
Else
shQuery.UsedRange.ClearContents
End If
q = q + 1
End If '<-- Added line
Err = 0 '<-- Added line
Next i
End Sub

Related

How do I get errors only for the files that error out

At my company we need to convert a lot of text files each month to excel and some of the columns we need to change the data types of the columns. They used to convert all of them manually which was very time consuming. I created an access program that they can do it in much easier. They just hit a button and it transfers them, with a running list of all the files converted. Some of the files will change here and there, so when running the program I have another list that is supposed to show all the files that cause an error. Unfortunately, what it does, at the moment, once it receives the error from one file - every file after that also says there is an error. So if there are 100 files witch file 5 and 25 as errors, it would still show all files from 5 to 100 are errors. Here is the code I am using:
Public Sub ImportTextFile(ByVal xl As Excel.Application, ByVal strFileName As String, ByVal iNumOfCols As Integer, Optional aDataTypes As Variant = Nothing)
On Error GoTo Sub_Err
Dim sPathAndFile As String: sPathAndFile = cPath & strFileName
Dim wb As Workbook: Set wb = xl.Workbooks.Add
Dim ws As Worksheet: Set ws = wb.Sheets(1)
With ws.QueryTables.Add(Connection:="TEXT;" & sPathAndFile & ".txt", Destination:=ws.Range("$A$1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = GetColumnDataTypes(iNumOfCols, aDataTypes)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Call SaveFile(wb, sPathAndFile)
Forms("Dashboard").lbCompleted.AddItem strFileName
Forms("Dashboard").lbCompleted.Selected(Forms("Dashboard").lbCompleted.ListCount - 1) = True
Sub_End:
Set wb = Nothing
Set ws = Nothing
Err.Clear
Exit Sub
Sub_Err:
'MsgBox Err.Description
Forms("Dashboard").lbError.AddItem strFileName
Resume Sub_End
End Sub
and then each file calls back like this:
Call ImportTextFile(xl, "DGXC094P", 11)
Call ImportTextFile(xl, "DGAC081", 18, Array(, , , , , , , , , , , , , , , , , , 2))
I tried clearing the error but it doesn't clear. What am I doing wrong? How can I get it to show only the files that have errors?
Concerning the Sub to import the Textfile: Make it a function. Then you are able to give a callback if there was an error or not. Like this:
Public Function ImportTextFile(ByVal xl As Excel.Application, ByVal strFileName As String, ByVal iNumOfCols As Integer, Optional aDataTypes As Variant = Nothing) as string
On Error GoTo ErrorHandling
Dim sPathAndFile As String: sPathAndFile = cPath & strFileName
Dim wb As Workbook: Set wb = xl.Workbooks.Add
Dim ws As Worksheet: Set ws = wb.Sheets(1)
With ws.QueryTables.Add(Connection:="TEXT;" & sPathAndFile & ".txt", Destination:=ws.Range("$A$1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = GetColumnDataTypes(iNumOfCols, aDataTypes)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Call SaveFile(wb, sPathAndFile)
Forms("Dashboard").lbCompleted.AddItem strFileName
Forms("Dashboard").lbCompleted.Selected(Forms("Dashboard").lbCompleted.ListCount - 1) = True
Set wb = Nothing
Set ws = Nothing
ImportTextFile = "ok"
Exit Function
ErrorHandling:
Set wb = Nothing
Set ws = Nothing
ImportTextFile = Err.Description
End Function
Your procedure to call the function should look like this:
Dim ImportResult as string
ImportResult = ImportTextFile(xl, "DGAC081", 18, Array(, , , , , , , , , , , , , , , , , , 2))
'Case Import Error
If ImportResult <> "ok" then
MsgBox (ImportResult)
Forms("Dashboard").lbError.AddItem strFileName
end if
'Case Import OK
If ImportResult = "ok" then
'What you want
end if
When using a function instead of a sub you will be able to treat each import individually.

Want to import bits (a couple of rows) of an .txt to excel

Hey so i found a specific query to import a file into excel from a specific row and delete the following datga each time you open it again. but is it also pssible to stop adding rows at a specific line? and is it possible to leave some rows out if there for example is a specific word in that line?
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
You can do it, but not with a Querytable.
Try this code:
Private Sub Open_Click()
Dim fn As Variant, myLine As Long, txt As String, x As Variant, ouput As String
Dim i As Integer, j As Integer: j = 1
Dim sht As Worksheet
Set sht = Worksheets("Sheet1") 'Modify Sheet Name
fn = Application.GetOpenFilename("Text Files (*.txt),*.txt", , _
"Open File")
If fn = False Then Exit Sub
txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(txt, vbNewLine)
For i = 0 To UBound(x)
If x(i) <> "SomeCriteria" Then 'Check for some criteria
sht.Cells(j, 1).Value = x(i)
j = j + 1
End If
Next i
End Sub
So what it does basically, it opens a user selected txt file and stores it in the variable txt. Do seperate the rows you can use the split-function. Now each line is stored in an array x. You could go trough the array/each line and take out the ones you want. To check if a specific word is in a line, use the InStr-function.

How to read from a text (.txt) file and place data into an excel 2016 document using VBA Macros editor?

I need to read the following text document (see first picture):
and place data into an excel document in the pictured manner (see second image):
I want to do this with an Excel VBA macros but I do not have the slightest idea on how to do so. I am very new to excel VBA and I do not have the slightest idea on where to begin.
Use following sub.
Sub txtImport()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\HARUN\Documents\Test.txt", Destination:=Range("$A$1"))
.Name = "Test"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
This code will do that without looping and regardless of number of spaces between the columns.
Sub Test()
Dim Fn As String, WS As Worksheet, st As String
Fn = "D:\tttt\test.txt" ' the file path and name
Set WS = Sheets("Sheet1")
'Read text file to st string
With CreateObject("Scripting.FileSystemObject")
If Not .FileExists(Fn) Then
MsgBox Fn & " : is missing."
Exit Sub
Else
If FileLen(Fn) = 0 Then
MsgBox Fn & " : is empty"
Exit Sub
Else
With .OpenTextFile(Fn, 1)
st = .ReadAll
.Close
End With
End If
End If
End With
'Replace every one or more space in st string with vbTab
With CreateObject("VBScript.RegExp")
.Pattern = "[ ]+"
.Global = True
.Execute st
st = .Replace(st, vbTab)
End With
'Put st string in Clipboard
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.SetText st
.PutInClipboard
End With
'Paste Clipboard to range
WS.Range("A1").PasteSpecial
End Sub
Let's suppose you have csv file (like you have shown, just difference is in delimiters), then the code should be:
Sub ReadData()
Dim line, array() As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set rfile = FSO.OpenTextFile(*your full path to the file*, 1) 'connection for reading
Dim i As Integer
i = 1
Do Until rfile.AtEndOfStream
line = rfile.ReadLine
array = Split(line, ",") 'I assumed that delimiter is comma
For j = 0 To UBound(array)
Cells(i, j + 1).Value = array(j)
Next j
i = i + 1
Loop
rfile.Close
End Sub

Data from website passing variable name to URL but not going to the correct website

This code is basically working correctly but for some reason the data it pulls is not changing. As I step through the Name_of_Person variable is changing as I move through the X's and the URL created and used changes every time but it keeps inserting the data from the first query. Any thoughts as to why?
Sub Search_People()
Dim Name_Of_Person As String
Dim URL As String
Dim Dashboard_Sheet As Worksheet
Set Dashboard_Sheet = ThisWorkbook.Sheets("Dashboard")
Dim Data_Sheet As Worksheet
Set Data_Sheet = ThisWorkbook.Sheets("Data")
Dim Data_Dump As Worksheet
Set Data_Dump = ThisWorkbook.Sheets("DataDump")
Dim X As Integer
Dim Y As Integer
Dim Last_Row As Long
Dim Email_Output As Range
Set Email_Output = Data_Dump.Range("A:A")
Dim Cell As Range
Last_Row = Data_Sheet.Cells(Data_Sheet.Rows.Count, 8).End(xlUp).Row
For X = 1 To Last_Row + 1
Name_Of_Person = Data_Sheet.Cells(2 + X, 8)
URL = "URL;" & "https://hn.com/people/"
URL = URL & Name_Of_Person & "%40.com"
With Data_Dump.QueryTables.Add(Connection:= _
URL, _
Destination:=Data_Dump.Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
Set Cell = Email_Output.Find("Email")
Worksheets("Data").Cells(2 + X, 9).Value = Cell
End With
Data_Dump.Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Next X
End Sub
Sub Search_People()
Dim Name_Of_Person As String
Dim URL As String
Dim Dashboard_Sheet As Worksheet
Set Dashboard_Sheet = ThisWorkbook.Sheets("Dashboard")
Dim Data_Sheet As Worksheet
Set Data_Sheet = ThisWorkbook.Sheets("Data")
Dim Data_Dump As Worksheet
Set Data_Dump = ThisWorkbook.Sheets("DataDump")
Dim X As Integer
Dim Y As Integer
Dim Last_Row As Long
Dim Email_Output As Range
Set Email_Output = Data_Dump.Range("A:XFD")
Dim Cell As Range
Application.EnableCancelKey = xlDisabled
Last_Row = Data_Sheet.Cells(Data_Sheet.Rows.Count, 8).End(xlUp).Row
For X = 1 To Last_Row
On Error Resume Next
Name_Of_Person = Data_Sheet.Cells(2 + X, 8)
Application.StatusBar = " Pulling Data for... " & Name_Of_Person
URL = "URL;" & "https://site/"
URL = URL & Name_Of_Person & "site.com"
With Data_Dump.QueryTables.Add(Connection:= _
URL, _
Destination:=Data_Dump.Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
Set Cell = Email_Output.Find("Email")
Worksheets("Data").Cells(2 + X, 9).Value = Cell
Data_Dump.Range("A:A").EntireColumn.Delete
Next X
Application.StatusBar = False
End Sub
This code solved all of the above issues.

Extract match data from this web "http://bet.hkjc.com/football/index.aspx?lang=en"

I want to extract match data from this web site "http://bet.hkjc.com/football/index.aspx?lang=en" using the following code :
Sub Macro4()
' Macro4 Macro
' steve lau 在 28/04/2016 錄製的巨集
baseURL = "http://www.hkjc.com/chinese/news/redirect_odds_ch_football.asp"
baseName = "summary"
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;" & baseURL _
, Destination:=Range("A1"))
End With
With ActiveSheet.QueryTables.Add(Destination:=Range("A1"))
.Name = baseName
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=True
End With
End Sub
But nothing was returned. I think it may due to different frames in the web page. Could anyone can help to figure out how to extract the match details ?
Many thanks.
You can use the following script where I grab the table using a
.document.getElementById("footballmaincontent").getElementsByTagName("table")(2)
and then loop the rows and columns (cells within row) within the table.
Sample results on page on 14/06/2018
Matches output from script:
Code:
Option Explicit
Public Sub GetInfo()
Dim IE As New InternetExplorer, a As HTMLTable
Const URL = "http://bet.hkjc.com/football/index.aspx?lang=en"
Application.ScreenUpdating = True
With IE
.Visible = False
.navigate URL
While .Busy Or .readyState < 4: DoEvents: Wend
Set a = .document.getElementById("footballmaincontent").getElementsByTagName("table")(2)
Dim r As Long, c As Long, iRow As HTMLTableRow, iCell As HTMLTableCell
With ActiveSheet
For Each iRow In a.getElementsByTagName("tr")
For Each iCell In iRow.getElementsByTagName("td")
Select Case iCell.innerText
Case "Home", "Draw", "Away"
Case Else
c = c + 1: .Cells(r + 1, c) = iCell.innerText
End Select
Next iCell
c = 0: r = r + 1
Next iRow
End With
.Quit
End With
Application.ScreenUpdating = True
End Sub
References required (VBE > Tools > References)
HTML Object Library
Microsoft Internet Controls