Finding a tab name using string - excel

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

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

Pushing data from Excel to Word throws error 5844 when text contains apostrophe

My Excel macro reads the values of a bunch of cells in Excel and pushes them to corresponding "content controls" in a Word template file. Everything works as planned unless the source cell contains a string with an apostrophe, e.g. "Children's Hospital". In this case execution stops:
"Run time error 5844 One of the values to this method or property is incorrect".
I have tried to read the cell value into an auxiliary string variable before assigning that to the content control but that did not help.
I also tried to force the source value to string using the CStr function - no good.
What do I do wrong?
Help please.
Sub PushToWord()
Dim oAppWord As Word.Application
Dim oDoc As Word.Document
...
With ThisWorkbook.Worksheets("Results")
...
oDoc.SelectContentControlsByTitle("Institution").Item(1).Range.Text = .Cells(18, iSCol).Value
...
End With
...

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.

Excel VBA : Move a picture to another sheet without copy/pasting

I am working on a project of a memory card game (where all cards are hidden and you have to find pairs of cards by looking at 2 cards at a time), so I made the code works with letters inside of cells and displaying "[x]" for hidden cards.
Now I am trying to move to images, the problem is : I can't just put the *.jpg in the folders, Images need to be embedded in the excel file, so I created a "Data" sheet with all my images (hidden and unhidden).
They are named as follow : "christmashidden", "christmasA", "christmasB" etc..
Now i wan't to have my macro to take these shapes and copy them to another worksheet (the "Plate" worksheet for instance) dynamically.
So i'm about to create a function like :
Function PlaceImgInCell(Target As Range, PairID As String, ThemeName As String) As Shape
'This function will be called by the main function to place a specific image in a specific cell
'and return the image shape object if any manipuation is needed afterward
Dim TargetImg As Shape
Dim BaseImg As Shape
Set BaseImg = ThisWorkbook.Worksheets("Data").Shapes(ThemeName & PairID) 'l'image de base, on la duplique pour la placer au bon endroit
BaseImg.Copy
but I think that copying and pasting each relevant shape everytime we need to change from hidden to shown might be long to display and not efficient, but i don't know any other way to do, what are the options at my disposal ? Thanks !

Executing VBA function from current workbook in cell formula get error #name (#nom for French version)

I meet a problem which is probably very simple when I use a VBA function into a formula of a cell, I get the cell content "#NAME" (not found function ? while a macro using the function (for test) is executed normally (displays the wished content for the cell, the returned value by the function, which extracts the filename from a fullpath).
context :
I had by the past (more than 12 years ago) developed, may be 50,000, VBA instructions, using office2003.
Today I have to develop again some macros with Office365. So I have forgotten a lot since this time and some features can have changed which can become tricking (I need to read again my old soft to recall all my knowledge, but I have no access to for now)
The problem
I get the error "#name" when I use a function created into VBA
associated to the current workbook. No explanation, no help, I tried to
find something during several hours and I found nothing.
I have developed too for testing (see code) a "sub" which calls the function, and his execution is successful, but...
I cannot run the function from the formula of any cell.
I have tested the security parameters of macro and fully unlocked the execution temporarily, and too declare the local directory as confident area.
Note : this code is detailed as an example
The code
Public Function FNameOf(CellPointed As Range)
Dim CurCell As Range
Dim Text1 As String
Dim Text2 As String
Set CurCell = CellPointed
Text1 = CurCell.Value
Text2 = Mid$(Text1, InStrRev(Text1, "\") + 1, Len(Text1))
FNameOf = Text2
End Function
Sub DispFileName2()
Dim style, disp, titre
Dim Cursel As Range
'Cursel = ActiveCell
disp = FNameOf(ActiveCell)
style = vbOKOnly
titre = "Nom du fichier extrait du texte (fullpath) de la cellule courante"
MsgBox disp, style, titre
End Sub
If I submit the macro DispFileName2 if get the message with the file name extracted from the path which is the content of the current cell
If I set the formule of a cell :
=FNameOf(AnotherCell) 'which contains a fullpath to a file
I get always the error "#NOM" (in French version) or, I think so, "#NAME" (in english Version) as if the function name (ref) was unknown from the workbook (the code is not reached, a stop is set on the first instruction)
What can be the reason ?
Please place your user defined function somewhere in a module (neither in "ThisWorkbook" nor in the individual worksheet's code, e. g. "Feuil1").
You should add the result declaration As String also.
I understood the example is for reference only, but you may shorten it:
Public Function FNameOf(CellPointed As Range) As String
FNameOf = Mid(CellPointed.Value, InStrRev(CellPointed.Value, "\") + 1)
End Function
I just got the solution while reading in more details previous edited threads in several tabs.
It is explained into a remark of : thread 12351339
The text is :
Microsoft Excel Objects such as 'Sheet1' or 'ThisWorkbook' are
classes. I don't believe you can access Functions which you put in
these classes through a cell. You could access them in VBA e.g.
ThisWorkbook.Square2() but it's recommended to put all UDF's into as
standard module and not a worksheet module. – Eddie Sep 28 '17 at
13:49
By default the creation panel defines code associated to current worksheet, then the function is not visible for the worksheet while the sub is a macro of the worksheet.
I have created a module and the function has run immediately.
Best regards
Trebly
Note : I never met this problem of visibility before because the developments where since the beginning concerning VBA user classes and modules combining multiple Excel workbooks and Word and a Mail manager activeX and so on...
I keep the subject because of the explanations, code and keywords may be to find more easily the solution for anybody else.

Resources