Script de ejemplo para seleccionar un fichero excel y leerlo.
El siguiente ejemplo solicita en pantalla un fichero y lee sus columnas.
Código VB6:
Dim fso, lFichero
lFichero = SelectFile()
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(lFichero) Then
MsgBox "Fichero " & lFichero & " no existente"
Exit Sub
End If
If MsgBox("¿Desea Importar el fichero de Excel seleccionado?",VBYesNo,"Importar Pedido del Cliente") = VBYes Then
Importa_Excel lFichero
End If
Function Importa_Excel (lFichero)
lFilaALeer = 2 'Fila sobre la que empezaremos a leer, normalmente la 1 es el nombre de las columnas
Set objExcel = CreateObject("Excel.Application")
' Apertura del fichero xls
objExcel.Workbooks.Open lFichero,,False
' Seguirá leyendo mientras no encuentre una celda en blanco (en la columna A)
While Len("" & objExcel.ActiveWorkbook.Sheets(1).Application.Cells(lFilaALeer, 1)) > 0
lDatoARecuperarColumna1 = objExcel.ActiveWorkbook.Sheets(1).Application.Cells(lFilaALeer, 1)
lDatoARecuperarColumna2 = objExcel.ActiveWorkbook.Sheets(1).Application.Cells(lFilaALeer, 2)
...
lFilaALeer = lFilaALeer + 1
Wend
objExcel.Quit
Set objExcel = Nothing
End FunctionCódigo VB6:
using Ahora.Excel;
using AhoraCore;
using AhoraOCX;
using System;
using static AhoraCore.VBA.Interaction;
namespace AhoraScriptsVacia
{
public class Script_71 : AhoraOCX.AhoraBaseScript
{
public void Main()
{
ICommonDialogUsuario CDFile = new CommonDialogUsuario();
CDFile.Flags = FileOpenConstants.cdlOFNFileMustExist;
CDFile.InitDir = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
CDFile.Filter = "Todos los archivos (*.*)|*.*|Hojas de Cálculo |*.xls;*.xlsx";
CDFile.FilterIndex = 2;
CDFile.DialogTitle = "Seleccione un fichero Excel";
CDFile.ShowOpen();
if (CDFile.FileName != null && CDFile.FileName != "")
{
string lRuta = CDFile.FileName;
int lFilaALeer = 2;
Valor lDatoARecuperarColumna1;
Valor lDatoARecuperarColumna2;
IExcelApplication oExcel = AhoraCore.AhoraServiceLocator.Current.GetService<Ahora.Excel.IExcelApplication>();
if (oExcel.ExcelInstalado())
{
oExcel.Workbooks.Open(lRuta, null, false);
bool lSigueLeyendo = true;
while (lSigueLeyendo)
{
lDatoARecuperarColumna1 = oExcel.ActiveWorkbook.Sheets[1].get_Cells(lFilaALeer, 1).Value;
lDatoARecuperarColumna2 = oExcel.ActiveWorkbook.Sheets[1].get_Cells(lFilaALeer, 2).Value;
// ...
if (lDatoARecuperarColumna1 == "" || lDatoARecuperarColumna2 == "")
{
lSigueLeyendo = false;
}
else
{
MsgBox(lDatoARecuperarColumna1);
MsgBox(lDatoARecuperarColumna2);
}
lFilaALeer++;
}
oExcel.Quit();
oExcel = null;
}
}
}
}
}