Problema con la función .Refresh BackgroundQuery:=True
Resuelto
Aymericci
-
Aymericci -
Aymericci -
Hola a todos,
Acabo de recuperar un programa que proviene de otra computadora y que permite obtener datos de la máquina de medición.
Por lo tanto, me gustaría adaptar el código a mi computadora y mi máquina, pero no funciona.
Cuando ejecuto la macro, aparece el error 1004: Imposible encontrar el archivo de texto para la actualización de esta área de datos externos. Asegúrese de que el texto no haya sido movido ni renombrado, y vuelva a intentarlo.
No tengo mucho conocimiento en VBA y me gustaría saber si alguien tendría una solución a mi problema. Copio a continuación la parte del código que falla. Es la última línea Refresh BackgroundQuery := True la que se indica en amarillo durante la depuración.
Les agradezco su ayuda,
Aymeric
Dim oFso As Object
Dim amountfiles As Integer
Dim IQ As String
IQ = Cells(10, 1).Text
Set oFso = CreateObject("Scripting.FileSystemObject")
amountfiles = Count_Subfolders(oFso, IQ & ":\DATA\")
Set oFso = Nothing
Dim Batch As Integer
'Starting loop function
Dim i As Integer
Dim name As Integer
Dim file As String
Dim location As String
For i = 1 To amountfiles
name = 0 + i
If i <= 9 Then
file = "BATCH" & ".00" & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
Else
If i <= 99 Then
file = "BATCH" & ".0" & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
Else
file = "BATCH" & "." & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
End If
End If
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & location & fname, Destination:=Range("A1"))
'With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & "H:\DATA\BATCH.001\stats.csv" & fname, Destination:=Range("A1"))
.name = "stats"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
Acabo de recuperar un programa que proviene de otra computadora y que permite obtener datos de la máquina de medición.
Por lo tanto, me gustaría adaptar el código a mi computadora y mi máquina, pero no funciona.
Cuando ejecuto la macro, aparece el error 1004: Imposible encontrar el archivo de texto para la actualización de esta área de datos externos. Asegúrese de que el texto no haya sido movido ni renombrado, y vuelva a intentarlo.
No tengo mucho conocimiento en VBA y me gustaría saber si alguien tendría una solución a mi problema. Copio a continuación la parte del código que falla. Es la última línea Refresh BackgroundQuery := True la que se indica en amarillo durante la depuración.
Les agradezco su ayuda,
Aymeric
Dim oFso As Object
Dim amountfiles As Integer
Dim IQ As String
IQ = Cells(10, 1).Text
Set oFso = CreateObject("Scripting.FileSystemObject")
amountfiles = Count_Subfolders(oFso, IQ & ":\DATA\")
Set oFso = Nothing
Dim Batch As Integer
'Starting loop function
Dim i As Integer
Dim name As Integer
Dim file As String
Dim location As String
For i = 1 To amountfiles
name = 0 + i
If i <= 9 Then
file = "BATCH" & ".00" & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
Else
If i <= 99 Then
file = "BATCH" & ".0" & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
Else
file = "BATCH" & "." & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
End If
End If
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & location & fname, Destination:=Range("A1"))
'With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & "H:\DATA\BATCH.001\stats.csv" & fname, Destination:=Range("A1"))
.name = "stats"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
1 respuesta
yg_be
Mensajes publicados
23437
Fecha de registro
Estado
Colaborador
Última intervención
Ambassadeur
1 588
buenas noches, parece que el mensaje de error te indica que no se puede encontrar el archivo de texto que quieres importar.
en el momento de depurar, ¿cuáles son los valores de "location" y de "fname"? puedes encontrarlos colocando el cursor sobre esos nombres.
en el momento de depurar, ¿cuáles son los valores de "location" y de "fname"? puedes encontrarlos colocando el cursor sobre esos nombres.
solo nos muestras una parte del código, difícil para nosotros ser más precisos.
Opción explícita
Public Sub Count_Subfolders_Test()
Dim oFso As Object
Dim amountfiles As Integer
Dim IQ As String
IQ = Cells(10, 1).Text
Set oFso = CreateObject("Scripting.FileSystemObject")
amountfiles = Count_Subfolders(oFso, IQ & ":\DATA\")
Set oFso = Nothing
Dim Batch As Integer
'Iniciando la función de bucle
Dim i As Integer
Dim name As Integer
Dim file As String
Dim location As String
For i = 1 To amountfiles
name = 0 + i
If i <= 9 Then
file = "BATCH" & ".00" & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
Else
If i <= 99 Then
file = "BATCH" & ".0" & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
Else
file = "BATCH" & "." & name
location = IQ & ":\DATA" & "\" & file & "\" & "stats"
End If
End If
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & location & fname, Destination:=Range("A1"))
'With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & "H:\DATA\BATCH.001\stats.csv" & fname, Destination:=Range("A1"))
.name = "stats"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
Next i
' eliminar columnas
Dim del As Integer
For i = 1 To amountfiles
del = 3 + i
Columns(del).Select
Selection.delete Shift:=xlToLeft
Next i
Range("C3:HC43").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("C3:HC3") _
, SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
"BATCH.001,BATCH.002", DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("C3:HC43")
.Header = xlGuess
.MatchCase = True
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
ActiveWindow.SmallScroll Down:=-15
Range("B2").Select
End Sub
Private Function Count_Subfolders(oFso As Object, folderPath As String) As Long
Dim Folder As Object, Subfolder As Object
Set Folder = oFso.GetFolder(folderPath)
Count_Subfolders = 0
For Each Subfolder In Folder.Subfolders
Count_Subfolders = Count_Subfolders + 1 + Count_Subfolders(oFso, Subfolder.path)
Next
End Function
¿Cómo se llama el archivo a importar que se encuentra en G:\DATA\BATCH001\stat?
¿Tiene el mismo nombre en las otras carpetas?
Por si acaso: añade debajo de
Finalmente encontré el error, estaba en el camino de acceso, no era batch sino ensayo, tanta costumbre de hablar de batch que no me había dado cuenta de que en este instrumento estaba traducido. ¡De todos modos, te agradezco muchísimo por tu ayuda!
¡Felices fiestas!