How change the file in every turn of loop - excel

I'm new at vba and I'm trying to create a form in excel with removable lists with items taken from another excel book which contains the items I need for the list.
At the same time as I want to change the label values dynamically I made a loop For Next which change the value of the label in every turn.
I need to say before you see the code that I changed the labels name to start at 0 instead 1 so my 1st label is called label0 and not label1, I made this because I created an array with the names I need for labels.
I tried to do this:
Private Sub UserForm_Initialize()
'Declarando variables
Dim file As Workbook 'variable que contiene el libro con la tabla de los archivos
Dim var As Long 'variable que para el bucle for
Dim i As Long 'variable para el bucle for
Dim label As Variant
'Creamos una array que contenga los nombres posibles de label
label = Array("Dirección", "Empresa", "Area/Planta del suceso")
'Asignamos los valores para las variables de departamentos y empresas que abrirán los respectivos archivos que se encuentran en la ruta especificada
Set file = Workbooks.Open("C:\Users\se72497\Desktop\Departamentos.xlsx")
For var = 0 To 2
'Asigna el nombre a las etiquetas
Controls("label" & var).Caption = label(var)
'Bucle que recorre cada una de las líneas que existen en la tabla de DEPARTAMENTOS y se añaden a la lista desplegable que se especifica
For i = 2 To file.Sheets("Hoja1").Range("C2").End(xlDown).Row
direccion.AddItem file.Sheets("Hoja1").Cells(i, 3).Value
Next i
Next
file.Close
End Sub
I'm trying the variable file change every time the loop returns to the For var because when label2.caption is equal to label(2) for example needs another file than when it is label1.caption=label(0) I dont know if create another array with the files path, i suppose I can do that but if anyone know another way please let mw know.

Related

How can I turn on Data/Filter mode on Excel sheets from MATLABvia ActiveX?

My MATLAB code produces data that I want to send to Excel. I use ActiveX Server in MATLAB to both produce the Excel file and to do the export (I can control more properties of the resulting Excel file this way than by using the 'writetable' command). In the produced Excel file, I manually have to chose the menu 'Data/Filter' to turn on the function letting me filter and sort each column (visible as the small triangles in the column headings as shown in the illustration below).
How can I turn on this function with ActiveX from MATLAB?
Call the AutoFilter method on an Excel Range object. For example, if you have a worksheet object MySheet:
rangeToFilter = get(MySheet,'Range','A1:B3');
rangeToFilter.AutoFilter
You can use a simple function that helps you to get the range depending on the size of the data that you will send to excel. For example:
idx2=size(data,2);
rangeToFilt=join(["A1:",idxtoexcel(idx2),"1"],"");
rangeToFilt.AutoFilter
function rexcel=idxtoexcel(idx)
% Función que permite obtener el número y letra de las filas y columnas que ocupará una matriz a imprimirse en un libro de excel.
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if idx < 27
rexcel = alphabet(idx);
else
idx2 = rem(idx,26);
if idx2 == 0
rexcel = [alphabet(floor(idx/26)-1),'Z'];
else
rexcel = [alphabet(floor(idx/26)),alphabet(idx2)];
end
end

Exporting Access Database with Errors

i have access to an MS Access database connected with oracle (I just have permissions to view and copy information, not to edit):
And I Found some rows with value '#Error':
When I click on an error row, this warning is displayed:
I want to export this database but this warning appears again and exportation process fail.
I build a macro that can export the db but it isn't exporting ALL the data:
The result of the export is an excel file with 65534 rows and my db has 72437 rows! the are 6903 rows with value information which my macro doesn't pull into the excel file.
And I have a macro I used to pull the data from access and before this #Error rows appears, it had been working successfully:
Public Sub Bajada_OIT()
Sheets("OIT").Select
'variable para almacenar la conexion
Dim conexion As Object
'variable para almacenar los datos de la consulta al fichero access
Dim recordSet As Object
'variable con la consulta SQL
Dim consulta As String
'viarable donde almacenamos la cadena de conexión
Dim cadenaConexion As String
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'instanciamos el objeto conexion
Set conexion = CreateObject("ADODB.Connection")
'elegimos el proveedor que vamos a usar y donde se encuentra nuestra base de datos
cadenaConexion = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\SEC\COST\COST\DIT\DIT.accdb"
'consulta que haremos a la base de datos
consulta = "SELECT * FROM ADAS_PCO_OIT;"
'abrimos la conexión
conexion.Open cadenaConexion
'ejecutamos la consulta y nos traemos los resultados (recordset)
Set recordSet = conexion.Execute(consulta)
On Error Resume Next
Sheets("OIT").Range("A2").CopyFromRecordset recordSet
'Este error es debido a que la base de datos tiene filas con valores #Error que no pueden ser copiados al portapapeles.
If Err.Number = -2147467259 Then
MsgBox "La base de datos contiene datos imposibles de copiar, se ha cancelado la extracción automática."
Remove_Bajada_OIT
Exit Sub
End If
On Error GoTo 0
'cerramos el recordset
recordSet.Close
Set recordSet = Nothing
'cerramos conexion
conexion.Close
Set conexion = Nothing
MsgBox "Extraccion de Acces: ADAS_PCO_OIT (OIT) Satisfactoria.", vbInformation, "Ayuda"
End Sub
What would be the appropriate SQL query so that the errors are not displayed and the macro works again?
Or what configuration would I have to do in the database so that these errors do not appear (remember that I am not the administrator of this database)?
I Could resolve this problem doing the connection again in a new Access file:
Creating a new Access Blank desktop database.
On the External Data ribbon, choose the option "ODBC Database" That is in Import & Link Section.
Choose the source and destination area (you can specify how and where you want to store the data in the current database).
Create a New DSN File Data Source.
Select the driver for which you want to set up a data source (In my case, i use the "Oracle in OraClient12Home 1_32bit" 12.01.00.02 Driver Version)
Type the name of the file data source you want to save this connection.
Finish (Next you need to have accession privileges for enter the database if it has user/pw security).
It seems that my Data base connection had corrupted and doing this steps again has solved my problem.
I Hope this solution may solves this problem if anyone has the same trouble.

Why CHOOSE FUNCTION nested does not work without apparent visible error in MS Excel?**

I have a comments in cell F4 from a data base in HTML and looks like this (in spanish)
<b>[2020-02-04 12:15:45]:</b> Se aguarda la llegada de materiales. Hoy llega el material a sitio. Mientras, estamos realizando auditoria en BH715.
<br>
<b>[2020-01-31 15:16:58]:</b> COMENTARIO ASIGNACION: Se reasigna a otro supervisor por vacaciones.
So... I want to clean the text deleting (html tags):
"" , ":", ""
and the result will be:
[2020-02-04 12:15:45] Se aguarda la llegada de materiales. Hoy llega
el material a sitio. Mientras, estamos realizando auditoria en BH715.
[2020-01-31 15:16:58] COMENTARIO ASIGNACION: Se reasigna a otro
supervisor por vacaciones.
The two functions nested are using:
=SUBSTITUTE(F4;CHOOSE({1\2\3};"<b>";":</b>";"<br>");"")
But, only work the first number {1... of the range.
The rest of the number it doesn't work.
official Help here:
https://support.office.com/en-us/article/use-array-constants-in-array-formulas-477443ea-5e71-4242-877d-fcae47454eb8
any advice about that ?
I am using Office 2019/265 the delimiter are semicolons in my case.
thanks a lot.

Finding a tab name using string

The problem is that I don't know the exact code to find a tab using a variable.
For now my macro create a new tab in another workbook using the Range D26 as the name of my active workbook and is able to copy my form in the other workbooks but not in the right sheets. In fact it just send me to the debug.
Dim Titre As String
Titre = Range("D26").Value
Workbooks.Open "C:\Users\charl\Desktop\Programe comptable projet\Menu automatisé Test\Feuille de projet.xlsx"
Workbooks("Feuille de projet.xlsx").Worksheets(Titre).Range("B2") = Workbooks("Menu Automatisé.xlsm").Sheets("Fiche de création de projet").Range("D8").Value
I expect the program to copy of my form in the other workbooks in the tab I just created using the button. (The tab is created first)
Never mind I just found why it's not working. I was not precise enough for my string variable.
Dim Titre As String
Titre = Workbooks("Menu Automatisé.xlsm").Sheets("Fiche de création de projet").Range("D26").Value

Getting attachment in vb.net from gmail

Here's my code to retrieve attachment from Gmail message
Dim attachPart As MessagePartBody = myGMailService.Users.Messages.Attachments.Get(ProfileUsager.GoogleAccountUserName, ID, attachmentID).Execute()
Dim fileByteArray() As Byte = Convert.FromBase64String(attachPart.Data())
My problem is Convert.FromBase64String, this return:
L'entrée n'est pas une chaîne Base 64 valide, car elle contient un caractère non-Base 64, plus de deux caractères de remplissage ou un caractère non conforme parmi les caractères de remplissage.
How I can resolve this? This code is a code block I found on Google API doc.

Resources