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

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

Related

Merge multiple cells into one merged cell with line spacing

I was working on an excel template to make quotes. This template has a list of materials which you can validate so that a quote is automatically generated.
In itself, the template works fine, the problem appears when I try to add a new function, which will allow you through "UserForm" to insert a new item to the list.
Before this function, I was using the "=CONCATENATE" command to drag several items from the list to the final quote and added a "CHARACTER(10)" so that there is a line spacing between each item because it must appear in unified cells so that then the command "=SHEARCHV" returns all the items. When trying to automate this process, I realize that when I add a new row to the list, it is not added to the list of "=CONCATENATE" so, even though it works in the total sum, the specific item never appears in the description of the items in the final quote.
here some captures
First Step: Check whatever item you want to add
Second Step: The item will move to another sheet to add taxes and prorate as well as labor
Third Step: After that I should send the items that are separated in a single cell and with a space between each one so that finally the function "=SHEARCHV" looks for the "Server Room" and returns me the description of the items like the next image
In the yellow format you can see how the template worked before adding this new function
What I want to do is that when adding a new item to the list I also add a function which can insert several cells in a combined multiple cells, so that there is a line spacing between each item
Main lenguaje: Spanish
Excel Download: https://drive.google.com/file/d/1xUxd7Ze6AB25MVfyxlY9dSlWUeQBTDCH/view?usp=sharing
VBA CODE TO ENTER NEW ITEM
Sheets("PREVISTA").Range("A25").EntireRow.Insert
Sheets("PRORRATEO").Range("A48").EntireRow.Insert
Sheets("HOJA DE DATOS").Range("A22").EntireRow.Insert
Sheets("HOJA DE DATOS").Range("A22") = 1
Sheets("HOJA DE DATOS").Range("C22") = 1
Sheets("HOJA DE DATOS").Range("B22") = TextBox1
Sheets("HOJA DE DATOS").Range("G22") = TextBox2
Sheets("HOJA DE DATOS").Range("E22") = "=G22*'DATOS DE INTERNET'!C2"
Sheets("HOJA DE DATOS").Range("H22") = "=G22*C22"
Sheets("HOJA DE DATOS").Range("I22") = "=G22*$I$2"
Sheets("HOJA DE DATOS").Range("J22") = "=G22*$J$2"
Sheets("HOJA DE DATOS").Range("K22") = "=G22*$K$2"
Sheets("HOJA DE DATOS").Range("L22") = "=(K22+J22+I22)*$L$2"
Sheets("HOJA DE DATOS").Range("M22") = "=(I22+J22+K22+L22)*C22"
Sheets("HOJA DE DATOS").Range("N22") = "=H22+M22"
Sheets("PRORRATEO").Range("C47").Copy: Sheets("PRORRATEO").Range("C48").PasteSpecial xlPasteAll
Sheets("PRORRATEO").Range("V47").Copy: Sheets("PRORRATEO").Range("V48").PasteSpecial xlPasteAll
Sheets("PRORRATEO").Range("X47").Copy: Sheets("PRORRATEO").Range("X48").PasteSpecial xlPasteAll
Sheets("PRORRATEO").Range("F48") = "=C48/$C$2"
Sheets("PRORRATEO").Range("G48") = "=F48*$D$17"
Sheets("PRORRATEO").Range("I48") = "=G48/($C$20+$C$3)"
Sheets("PRORRATEO").Range("J48") = "=I48*$F$9"
Sheets("PRORRATEO").Range("K48") = "=J48+G48"
Sheets("PRORRATEO").Range("O48") = "=N48+M48+L48+K48"
Sheets("PRORRATEO").Range("B48") = "=CONCATENAR(X48)"
If CheckBox1.Value = True Then
Sheets("PRORRATEO").Range("L48") = "=K48*L24"
ElseIf CheckBox2.Value = True Then
Sheets("PRORRATEO").Range("M48") = "=K48*M24"
ElseIf CheckBox3.Value = True Then
Sheets("PRORRATEO").Range("N48") = "=K48*N24"
Else
Sheets("PRORRATEO").Range("N48") = "=K48*N24"
End If
Sheets("PRORRATEO").Range("Q48") = "=O48/O5"
Sheets("PRORRATEO").Range("R48") = "=Q48*O6"
Sheets("PREVISTA").Range("C24").Copy: Sheets("PREVISTA").Range("C25").PasteSpecial xlPasteAll
Sheets("PREVISTA").Range("N24").Copy: Sheets("PREVISTA").Range("N25").PasteSpecial xlPasteAll
Sheets("PREVISTA").Range("P24").Copy: Sheets("PREVISTA").Range("P25").PasteSpecial xlPasteAll
Sheets("PREVISTA").Range("B12") = "=CONCATENAR(P12:P26)"
End If
End Sub ```
I hope I have expressed myself well, any help is welcome thanks

How change the file in every turn of loop

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.

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

VBA learner - function call on left-hand

just started learning VBA and in one of my lesson I get to work with dates. I wrote the following code:
Sub Aula11 ()
Dim data1 as date
Dim data2 as date
Dim diferençadatas as long
Data1 = Date
Data2 = #2/8/2018#
diferençadatas = data1 – data2
MsgBox = “Passaram” & diferençadatas & “dias desde o dia 8 de Fevereiro de 2018”
End Sub
When I hit run, I get the following message: "Compile error: Function call on left-hand side of assignement must return Variant or Object" on subroutine line (line 1).
I don't understand what's wrong, I used date functions before and the first line was the same. Sorry about my dumb question, just trying to learn something so differently from what I'm used to :D
As you are a learner, consider not using variable names with letters deviating from the 26 standard letters of the English alphabet. Thus, diferencadatas could become easily diferençadatas.
As a second best practice - please name the variables in English. Thus a colleague who does not speak Portuguese can also take over your code easily.
This works quite ok:
Sub Aula11()
Dim data1 As Date
Dim data2 As Date
Dim diferencadatas As Long
data1 = Date
data2 = #2/8/2018#
diferencadatas = data1 - data2
MsgBox ("Passaram" & diferencadatas & "dias desde o dia 8 Fevereiro de 2018")
End Sub

Assign contents of Excel cell to string variable in AutoIT [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am writing a script that I want to pull cell values from an Excel spreadsheet containing usernames and passwords. I wish to use two variables USERNAME and PASSWORD. I would like to use the data on each row and move down a row with each pass of the loop.
I have looked over Excel UDF included in AutoIT and ExcelCOM_UDF written by a third party. I cannot seem to find the answers I am looking for. This should be a very basic function of either of these, but I am having trouble.
I am not looking for a handout, so just a nice reference page is fine. BUT if you have a snippet of what I need, it will not hurt my feelings as I am not determined to write this code solely on my own.
My "A" column will contain the USERNAME variables, and the "B" column will contain my PASSWORD variables.
Added snippet of some code of what I have so far. I have not tried to pull anything from Excel yet, because I cannot find a command that seems to do what I am looking to do. Hopefully seeing the code will give a better picture of my goal.
I DO NOT WISH TO MODIFY THE SPREADSHEET PROGRAMMATICALLY, ONLY SET STRING VARIABLES FROM CELL TEXT.
...
$USERNAME = "usernameHere" ;I want to set this variable as the text from A1 of c:\test.xls
$PASSWORD = "passwordHere" ;I want to set this variable as the text from B1 of c:\test.xls
;Username Box
MouseClick("left",1179,488,1)
;Type username
Send($USERNAME)
;Password Box
MouseClick("left",1179,578,1)
;Type Password
Send($PASSWORD)
...
In order to read a spreadsheet containing a list of usernames and password. This function create an array with two dimensions. The first column contains usernames, the second the password. With this
#include <Array.au3>
#include <Excel.au3>
Func get_data_Excel($filePathExcel)
Local $error
Local $oExcel = _ExcelBookOpen($filePathExcel, 0)
$oExcel.Application.DisplayAlerts = False
$oExcel.Application.ScreenUpdating = False
$error = Int(#error)
Select
Case $error = 1
msgbox(16, "Erreur : Fermeture de l'application", "Code erreur _ExcelBookOpen : 1"&#CRLF&#CRLF&"Impossible de creer l'objet $oExcel avec _ExcelBookOpen")
Case $error = 2
msgbox(16, "Erreur : Fermeture de l'application", "Code erreur _ExcelBookOpen : 2"&#CRLF&#CRLF&"Impossible d'ouvrir le fichier "&$filePathExcel&" avec _ExcelBookOpen")
EndSelect
If $error > 0 Then
_ExcelBookClose($oExcel, 0) ; Close without save
Exit
EndIf
; Read column A (login) and column B (pwd)
_ExcelSheetActivate($oExcel, "sheet1")
$nb_columns = $oExcel.ActiveSheet.UsedRange.Columns.Count
$nb_rows = $oExcel.ActiveSheet.UsedRange.Rows.Count
Local $array_data_excel[$nb_rows][2]
Local $idx
For $idx = 0 To $nb_rows-1
$array_data_excel[$idx][0] = $oExcel.Activesheet.Cells($idx+1, 1).Value
$array_data_excel[$idx][1] = $oExcel.Activesheet.Cells($idx+1, 2).Value
Next
_ExcelBookClose($oExcel, 0)
_ArrayDisplay($array_data_excel, "Data from excel file")
EndFunc
And to use this function :
get_data_Excel("d:\users.xlsx")
#include <Excel.au3>
Local $MyUsernameArray[5] = [ "Hans", "Gerd", "Walter", "Klaus", "Peter" ] ;Your Username Array
Local $MyPasswordArray[5] = [ "12345", "I", "am", "so", "creative" ] ;Your Password Array
$oExcel = _ExcelBookNew(1) ;Set this to 0 if you want it to work in background
_ExcelWriteCell ( $oExcel, "Usernames", "A1" ) ;self explaining (i hope)
_ExcelWriteArray ( $oExcel, 2, 1, $MyUsernameArray ,1) ;^
_ExcelWriteCell ( $oExcel, "Passwords", "B1" );^
_ExcelWriteArray ( $oExcel, 2, 2, $MyPasswordArray ,1);^
_ExcelBookSaveAs($oExcel, #ScriptDir & "\PleaseAtleastPostSomeCodeNextTimeSoWeSeeYouTried", "xls") ;save the file
_ExcelBookClose($oExcel, 1, 0) ;exit and save
If you want to get all control with COM/Automation Excel, don't use the UDF , andd deep inside the Com/Automation with the function AutoIt ObjCreate. With this function you can get the control of the Object Excel in AutoIt
COM/Automation with Excel
1) Create reference on COM Object of target application (here this is Excel)
$oExcel = ObjCreate("Excel.Application")
2) Add some options on this instance
With $oExcel
.Visible = 1
.WorkBooks.Add
EndWith
3) And now the work can be begin (add some worksheet or data, save the workbook...)
With $oExcel
.ActiveWorkbook.Worksheets(1).Name = "SHEET_ONE"
.ActiveWorkbook.Worksheets(1).Cells(1,1) = "I believe i can fly !!!"
EndWith
Hacks 1 : Save As
; Create new file with one sheet named "SHEET_ONE"
Local $oExcel = ObjCreate("Excel.Application")
With $oExcel
.SheetsInNewWorkbook = 1
.Visible = 1
.WorkBooks.Add
.ActiveWorkbook.Worksheets(1).Name = "SHEET_ONE"
.ActiveWorkbook.Worksheets(1).Cells(1,1) = "I believe i can fly !!!"
EndWith
Local $filename = #WorkingDir&"\saveas_excel.xls"
$oExcel.Application.DisplayAlerts = 0
$oExcel.Application.ScreenUpdating = 0
$oExcel.ActiveWorkBook.SaveAs($filename, 1, Default, Default, Default, Default, 2, 1)
$oExcel.Quit
More information (in french) on http://www.autoitscript.fr/forum/viewtopic.php?t=3272&f=11

Resources