Visual Basic - Duda en macro

Life is soft - evento anual de software empresarial
 
Vista:

Duda en macro

Publicado por jesus10991 (1 intervención) el 17/05/2017 18:38:55
Hola, buenas tardes.

Tengo una macro, la cual utilizo para abrir el contenido de un fichero CSV y que éste se copie en la Hoja 4 del libro de Excel.
Todo funcionaba con normalidad, hasta que he tenido la necesidad de usar la aplicación de Excel en otro ordenador.

En el ordenador origen, tengo la aplicación y el archivo del cual deseo copiar los datos en la carpeta Documentos y en el nuevo ordenador lo tengo en otra carpeta distinta. He de decir, que si lo cambio a documentos, cortando los archivos, no haciendo un copiado, funciona perfectamente.
Pero me gustaría saber, en que línea de la macro se hace referencia a que la búsqueda se haga en la carpeta Documentos precisamente.

Y agradecería que me modificaseis la macro, para que buscase el archivo CSV, que como veis ha de llamarse "Importar", solamente en la misma carpeta en la que tenga guardado el Excel que contiene la macro.

Os pego la macro y os agradezco la atención.


Sub ImportAllCSV()
Dim FName As Variant, R As Long
R = 1
FName = Dir("Importar.csv")
Do While FName <> ""

Sheets("Hoja4").Select
ImportCsvFile FName, ActiveSheet.Cells(R, 1)

R = ActiveSheet.UsedRange.Rows.Count + 1
FName = Dir
Loop
End Sub

Sub ImportCsvFile(FileName As Variant, Position As Range)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & FileName _
, Destination:=Position)
.Name = Replace(FileName, ".csv", "")
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlMacintosh
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = ";"
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.Refresh BackgroundQuery:=False
End With
Sheets("Hoja1").Select
End Sub



Gracias, un saludo.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Antoni Masana
Val: 1.259
Plata
Ha mantenido su posición en Visual Basic (en relación al último mes)
Gráfica de Visual Basic

Duda en macro

Publicado por Antoni Masana (558 intervenciones) el 18/05/2017 15:41:43
Realmente no le das la ruta en ningún sitio de la macro.

No entiendo la primera función, el primer DIR te devuelve el nombre del fichero si existe, importa los datos y el segundo DIR devuelve NADA y finaliza el bucle. Para procesar mas ficheros debería en el primer DIR el asterisco o el signo de final de interrogación

Yo lo haría así

1
2
3
4
5
6
7
8
9
Sub ImportAllCSV()
    Dim FName As String
 
    FName = Dir("Importar.csv")
    IF  FName <> "" Then
        Sheets("Hoja4").Select
        ImportCsvFile FName, ActiveSheet.Cells(1, 1)
    End If
End Sub

Y vamos a tu problema. Tanto el Excel como el WORD se les configura para para una ubicación predeterminada ver:

Archivo -> Opciones -> Guardar -> Ubicación predeterminada de archivos locales

Y ahí es donde va a buscar Excel, para solucionarlo pon la ruta en el primer DIR y siempre ira a buscarlo al mismo sitio, en ejemplo a C:\Docume independientemente de como este configurado el Excel.

FName = Dir("C:\Documen\importar.csv")


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Sub ImportAllCSV()
    Dim FName As Variant, R As Long
    R = 1
    FName = Dir("Importar.csv")
    Do While FName <> ""
        Sheets("Hoja4").Select
        ImportCsvFile FName, ActiveSheet.Cells(R, 1)
 
        R = ActiveSheet.UsedRange.Rows.Count + 1
        FName = Dir
    Loop
End Sub
 
Sub ImportCsvFile(FileName As Variant, Position As Range)
 
    With ActiveSheet.QueryTables.Add(Connection:= "TEXT;" & FileName , Destination:=Position)
        .Name = Replace(FileName, ".csv", "")
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = xlMacintosh
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileOtherDelimiter = ";"
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .Refresh BackgroundQuery:=False
    End With
    Sheets("Hoja1").Select
End Sub

Con el código así se ve mejor.

Saldos.
\\//_
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar