Abrir Archivos con Código VBA

Cómo Abrir Archivos con VBA

Manejo de otros archivos en macros de VBA

Como programador, es probable que encuentre muchas situaciones en las que sea necesario aclarar otros archivos para deletrear, escribir o adicionar datos. Una macro puede ayudarlo a procesar estos archivos fácilmente, y el Extenso método es su boleto.

Ejemplos de escenarios de procesamiento de archivos de la vida actual

Aquí hay algunas aplicaciones donde puede usar este método:

  1. Los miembros del equipo actualizan su estado de trabajo en SharePoint.
  2. Actualice HP Quality Center a través de un complemento o una macro de Excel.
  3. Un avezado que marca la registro de ausencias en una hoja de Excel y usa un complemento (macro) que completa automáticamente la socorro de todos los estudiantes de la clase.
  4. Mantenga una almohadilla de datos de habilidades para los estudiantes y extraiga estos datos de varios libros de trabajo cuando sea necesario, como una lazo o un torneo.
  5. Las empresas crean y envían cotizaciones simplemente llenando un formulario. Por otra parte de las macros, igualmente se pueden utilizar plantillas para esto.

El método de archivo despejado de VBA

VBA proporciona un método obvio para aclarar y trabajar con archivos. Esto permite que un favorecido lea o escriba, o haga ambas cosas, a posteriori de aclarar el archivo.

Sintaxis:

Open <path name> For <mode> [Access access] [lock]

Explicación de los parámetros anteriores:

  1. : Un campo obligatorio. Es el nombre del archivo adjunto con los detalles de su extensión, mecanismo y carpeta.
  2. : Este es un campo obligatorio. Puede ser una de las cinco opciones siguientes:
    1. adicionar
    2. binario
    3. Salida:
    4. Aporte
    5. Fortuito: este es el modo predeterminado.
  3. Llegada: este es un parámetro opcional. Enumera las ediciones permitidas en el archivo despejado. Puede ser uno de los siguientes:
    1. Interpretar
    2. Escribe
    3. Lee y escribe
  4. Lock : Este igualmente es un parámetro opcional. Puede tener cualquiera de los siguientes títulos que están restringidos en el archivo despejado:
    1. Compartido
    2. Interpretar aislamiento
    3. Cerco de escritura
    4. Cerco de recital y escritura

Nota: Las etiquetas entre corchetes son opcionales. Aquí las etiquetas de llegada y aislamiento son opcionales.

Ejemplos de tolerancia de archivos con VBA

Ejemplo 1: solo abre un archivo

Este es un software simple que simplemente abre un archivo de Excel.

Sub open_file_demo()

' declare variable
Dim pathname

' assign a value
pathname = "C:UsersLAKSHMI RAMAKRISHNANDownloadsProject 1.xlsx"

' now open the file using the open statement
Workbooks.Open pathname

End Sub

Ejemplo 2: refugio un manual de Excel en modo de «solo recital» e intente escribir en él

Sub open_file_demo()

' declare variables
Dim pathname
Dim wb As Workbook

' assign a value
pathname = "C:UsersLAKSHMI RAMAKRISHNANDownloadsProject 1.xlsx"

' now open the file using the open statement and assign it to the wb object so that it can be used in the code further.
Set wb = Workbooks.Open(Filename:=pathname, ReadOnly:=True)

' Try writing after opening the file in "read only mode". This should throw an error.
wb.Sheets(0).Cells(1, 1).Value = "Try writing"

End Sub

Ejemplo 3: Cala un archivo de texto y lea su contenido con la función Rasgar y el número de archivo

Sub TextFile_PullData()

' declare variables

Dim int_txtfile As Integer
Dim str_file_Path As String
Dim str_File_Content As String

' Assign the file path to the variable
  str_file_Path = "C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentssample.txt"

' Find the next available file number to be used by the fileopen function
  int_txtfile = FreeFile

' Open the said text file using the function
  Open str_file_Path For Input As int_txtfile

' The content of the file is stored in a variable
  str_File_Content = Input(LOF(int_txtfile), int_txtfile)

' Print the file content using the variable in which it is stored
  Debug.Print str_File_Content

' Close the opened text file
  Close int_txtfile

End Sub
Uso del número de archivo para abrir y leer un archivo de texto

Ejemplo 4: deletrear y escribir contenido en un archivo de texto

En este ejemplo, primero abrimos un archivo de texto en modo de recital y copiamos su contenido en una variable. Luego cambiamos su contenido y abrimos el mismo archivo de texto en modo escritura. Finalmente, escribimos el contenido modificado en el archivo.

Sub txt_file_FindReplace()

Dim txt_file As Integer
Dim file_path As String
Dim file_content As String

' Assign the file path to the variable
  file_path = "C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentssample.txt"

' Determine the next available file number to be used by the FileOpen function
  txt_file = FreeFile

'  The text file is opened in read-only mode
  Open file_path For Input As txt_file

' Store the content of the file in a variable
  file_content = Input(LOF(txt_file), txt_file)

' Close the opened Text File
  Close txt_file
  
' Find and replace some text
  file_content = Replace(file_content, "It", "This file")

' Determine the next available file number to be used by the FileOpen function
  txt_file = FreeFile

' Open the text file in a Write State
  Open file_path For Output As txt_file
  
' Write the modified content to the file
  Print #txt_file, file_content

' Close the opened Text File
  Close txt_file

End Sub
Leer contenido y escribir el texto en un archivo de texto después de abrir

Ejemplo 5: adicionar datos a un archivo de texto

En este ejemplo, agregaremos texto adicional al final de un archivo de texto existente que ya contiene algunos datos.

Sub txt_file_append()

' declare variables

Dim int_txtfile As Integer
Dim str_file_Path As String
Dim str_File_Content As String

' Assign the file path to the variable
  str_file_Path = "C:UsersLAKSHMI RAMAKRISHNANOneDriveDocumentssample.txt"

' Find the next available file number to be used by the fileopen function
  int_txtfile = FreeFile

' Open the said text file using the function
  Open str_file_Path For Append As int_txtfile

' Write content to the end of the file
  Print #int_txtfile, "This is additional content"
  Print #int_txtfile, "Warm Regards"
  Print #int_txtfile, "Laksmi Ramakrishnan"

' Close the opened text file
  Close int_txtfile

End Sub
Abra y agregue texto adicional al final de un archivo.

Conclusión

Si acertadamente hay muchas formas de aclarar archivos con diferentes extensiones usando VBA, en este artículo hemos tratado de centrarnos en los métodos más básicos o simples para hacerlo.

El modo «despejado» en este aclarar documento El método juega un papel crucial en esto. Si intentamos adicionar o escribir en un archivo despejado en modo recital, se arroja un error que detiene la ejecución del software. Por lo tanto, puede pensar que el modo de recital proporciona «protección de datos» al archivo flamante que se abre.

Su Calificación Nos Ayuda a Mejorar