Refresh backgroundquery false ошибка

I’ve looked at some others with the same error but their solution doesn’t help me.

Refresh BackgroundQuery:=False Error 1004

Here is my code

'
' LoadData Macro
'

'
With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;Macintosh HD:Users:Karrar:Desktop:Excel.txt", Destination:=Range("A1"))
    .Name = "Excel"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .RefreshOnFileOpen = False
    .BackgroundQuery = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = False
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = xlMacintosh
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = True
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = True
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    .UseListObject = False
    .Refresh BackgroundQuery:=False
End With
End Sub

  • Remove From My Forums
  • Question

  • This might be a common problem and I found another topic that relates to mine but it isn’t quiet the same and I can’t find a solution to my problem by using it’s solution.

    I have a VBA script for getting data from a HTML table to a Excel file. At the HTML page the VBA script first logges in with a name and password written in the Excel file and given with the GET method.

    The HTML checks if the user is already logged in (session variables) and if so it gets the data from the table to Excel. If not the user is logged in and then the data is send.

    When I run the script it returns a 1004 error. This error is given at «.Refresh BackgroundQuery:=False».

    From using Google I understand that a 1004 error is given when the browser returns an errorcode that VBA doesn’t know.

    When I open the page (In both cases (with the username and password in the URL and already logged in without this)) in any browser (Safari, Firefox, Internet Explorer) the page doesn’t return any error nor report any problems with the page.

    My code:

    Sub GetData() 'Private Sub Workbook_Open() Private Sub Worksheet_Activate()<br/>
      Dim usr As String    'Username<br/>
      Dim pwd As String    'Password<br/>
      Dim url As String    'URL with username and password --> GET<br/>
      Dim baseUrl As String  'URL of page<br/>
      Dim connUrl As String  'URL for connection to HTML<br/>
      <br/>
      usr = ActiveSheet.Range("A1").Value<br/>
      pwd = ActiveSheet.Range("B1").Value<br/>
      <br/>
      baseUrl = "http://xxx/xx/xx/xx/xx/xx/xx.aspx"<br/>
      url = baseUrl & "?usr=" & usr & "&pwd=" & pwd<br/>
      connUrl = "URL;" & baseUrl<br/>
    <br/>
      'open Internet Explorer<br/>
      Set ie = CreateObject("InternetExplorer.Application")<br/>
    <br/>
      'go to .Navigate and show this<br/>
      With ie<br/>
        .Visible = True<br/>
        .Navigate url<br/>
    <br/>
        'do this until the page is fully loaded<br/>
        Do While ie.busy And Not ie.readystate = 4<br/>
          DoEvents<br/>
        Loop<br/>
        <br/>
        'create a Web Query in Sheet1 with connURL beginning from cell A5<br/>
        With ActiveSheet.QueryTables.Add(Connection:=connUrl, Destination:=Range("A4"))<br/>
          .Name = "stockListQuery"<br/>
          .RowNumbers = False<br/>
          .FillAdjacentFormulas = False<br/>
          .PreserveFormatting = True<br/>
          .RefreshOnFileOpen = False<br/>
          .BackgroundQuery = False<br/>
          .RefreshStyle = xlOverwriteCells<br/>
          .SavePassword = False<br/>
          .SaveData = True<br/>
          .AdjustColumnWidth = True<br/>
          .RefreshPeriod = 0<br/>
          .WebSelectionType = xlAllTables<br/>
          .WebFormatting = xlWebFormattingNone<br/>
          .WebPreFormattedTextToColumns = True<br/>
          .WebConsecutiveDelimitersAsOne = True<br/>
          .WebSingleBlockTextImport = False<br/>
          .WebDisableDateRecognition = False<br/>
          .WebDisableRedirections = False<br/>
          <br/>
          .Refresh BackgroundQuery:=False<br/>
          <br/>
        <br/>
        End With<br/>
        Do While ie.busy And Not ie.readystate = 4<br/>
          DoEvents<br/>
        Loop<br/>
        <br/>
      End With<br/>
      <br/>
      'close Internet Explorer<br/>
      ie.Quit<br/>
      <br/>
      Set ie = Nothing<br/>
    End Sub<br/>
    
    

Answers

  • Three suggestions

    1. Maybe you don’t have an active worksheet that you can write to.  Place the macro into a new workbook and see if you get the same error.  The worksheet may be protected.
    2. Try changing the URL to a different web page and see if you get an error
    3. Record a new macro and go to the same webpage and see if you get an error.

    jdweng

    • Marked as answer by

      Thursday, December 30, 2010 12:55 PM

  • #6

I am replying to this question a couple of years late.

I encountered the same problem today. When I was altering an excel application that use to run in Excel 97 so it can run in Excel 07. ( yes we are that much out of date at work) There was a querytable in the range A48 in the excel spreadsheet I wanted to refresh using the following VB code.

Range(«A48»).Select
Selection.QueryTable.Refresh BackgroundQuery:=False

«Selection.QueryTable.Refresh BackgroundQuery:=False» would not work in Excel 07.. after doing a far bit of googling I found a few people with the same porblem but not solution. So I recorded a macro in excel with me manually refreshing the the query (right click with the mouse on the selection «A48» and hit ‘refresh’ option on the drop down menu that appears) and looking at the macro code I got my code to work.

By changing

Selection.QueryTable.Refresh BackgroundQuery:=False

to

Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

The above piece of code worked!!!!

Last edited:

Sub Macro1()
Dim URL As String
Dim Path As String
Dim i As Integer
For i = 2 To 50
If Range("Prices!E" & i).Value <> 1 Then
URL = Range("Prices!D" & i).Text
Path = Range("Prices!F" & i).Text
End If
Sheet19.Activate
With ActiveSheet.QueryTables.Add(Connection:= _
    "URL;" & URL _
    , Destination:=ActiveSheet.Range("$A$1"))
    .Name = _
    "" & Path
    .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
    //'In the Line above the above
    //'Run time error '1004
    //'An unexpected error has occured
End With
Next i
End Sub

Приведенный выше код создает ошибку в указанной строке. Поиск в Google по .Refresh BackgroundQuery показывает, что он привередлив в своей функциональности в циклах. Простое удаление строки ничего не показывает в Excel.

С текущим сообщением об ошибке код отлично работает для первого значения i, а затем прерывается.

Для ответа и комментариев — TLDR: .Refresh BackgroundQuery:=False завершится ошибкой, если введенный вами запрос недействителен или искажен. Проблема в этом случае заключалась в том, что цикл for…next вызывал ячейки для использования в качестве URL-адресов, в которых не было значений. Однако он будет терпеть неудачу каждый раз, когда запрос будет искажен.

I have tried rewriting the code, but it was working fine before I tested it for about the 10th time and then it stopped working randomly.

Sub Titans()
 'Select Titans Worksheet
 Sheets("Titans").Select
 'Clear Contents
    Cells.Clear
    'Import data from Pro Football Reference
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;https://www.pro-football-reference.com/teams/oti/2022.htm#team_stats", Destination:= _
        Range("A1"))
        .PostText = "local"
        .Name = False
        .FieldNames = False
        .RefreshStyle = xlInsertDeleteCells
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .HasAutoFormat = True
        .RefreshOnFileOpen = 1
        .BackgroundQuery = False
        .TablesOnlyFromHTML = True
        .SaveData = True
        .Refresh BackgroundQuery:=False  ---> This is the line of code that stops it from running
    End With
End Sub

Eugene Astafiev's user avatar

asked Nov 12, 2022 at 9:04

tateml0000's user avatar

1

I tried running your macro, it ran simply fine in my system (office 365). Following was the output.
Output

I cannot figure out the error details as I cannot simulate it, but there is an alternative to this, you can load the web link in the web data connector and get the table.
As I see there are three tables on the web page, so the power query will recognize three individual table and give it as individual query. You would not require macro at all.

answered Nov 12, 2022 at 13:15

gogaci's user avatar

Понравилась статья? Поделить с друзьями:
  • Reflash 12345 ошибка
  • Redmond rmc m20 ошибка е1
  • Ref ошибка эксель
  • Relax player ошибка воспроизведения аудиозаписи
  • Relaunchusingcreateprocess createprocess failed ошибка