Parse a substring from ComboBox selection - excel

I have a ComboBox "Liste_cible" with values like: BOCAL SAP-A246, or PAP-SAP-K207.
I would like to use only the last number, after the "-" (A246 or K207) to run another subroutine.
I'm looking for the function like SUBTSTR(Me.Liste_cible.Value,”-“,-1)
Private Sub liste_cible_Change()
Dim argString As String
If Not Worksheets("1 - Feuille de Suivi Commercial").Liste_cible.MatchFound And Worksheets("1 -
Feuille de Suivi Commercial").Liste_cible <> "" Then
MsgBox "Saisie impossible, ce partenaire cible n'existe pas !", , "Contrôle"
Worksheets("1 - Feuille de Suivi Commercial").Liste_cible = ""
Else
Worksheets("1 - Feuille de Suivi Commercial").Cells(5, 17) = Worksheets("1 - Feuille de Suivi
Commercial").Liste_cible
MsgBox Me.Liste_cible.Value
argString = SUBTSTR(Me.Liste_cible.Value,”-“,-1) ??
GET_GROUPE_GESTION_CIBLE (argString)
INFO_PROTO1 (argString)
INFO_PROTO2 (argString)
End If
End Sub
MsgBox Me.Liste_cible.Value works correctly, but I don't know how to get the argString.

This should do the trick:
argString = Mid(Me.Liste_cible.Value, InStrRev(Me.Liste_cible.Value,"-") + 1)

Related

Same macro crashes in Excel 365 but works perfectly on Excel 2007

I got a macro that opens 2 workbooks and make some calculations. It works perfectly on Excel 2007 32 bit.
But in Excel 365 64 bits it crashes right after opening the first workbook, with no messages errors. Excel quits directly with no warning.
After some testing, I think it fails right after asking first workbook. The code is:
Sub PROCESO(ByVal EstasHojas As String)
Dim WBSource As Workbook
Dim WBDestiny As Workbook
Dim WKSource As Worksheet
Dim WKDestiny As Worksheet
Dim WBintermedio As Workbook
Dim WKIntermedia As Worksheet
Dim Ruta As String
Dim MiMatriz As Variant
Dim MatrizCampos As Variant
Dim LR As Long
Dim LC As Long
Dim i As Long
Dim j As Long
Dim MiF As WorksheetFunction: Set MiF = WorksheetFunction
Dim FechaPrevista As Long
Dim FechaReal As Long
Dim PagoEur As Long
Dim Proveedor As Long
Dim MatrizHojas As Variant
Dim NoHayDatos As Byte
Dim STRColor As String
Dim MatrizFinal() As Variant
Dim DictFechas As Object
Dim FechaDict As Variant
RutaCostIncomes = ""
RutaCashflow = ""
Application.Calculation = xlCalculationManual
'primero total hojas
MatrizHojas = Split(EstasHojas, "||")
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Seleccione archivo COST AND INCOMES"
.AllowMultiSelect = False
If .Show = False Then
MsgBox "No se ha seleccionado ningún archivo.", vbCritical, "PROCESO ABORTADO"
GoTo Final
Else
Ruta = .SelectedItems(1)
Set WBSource = Application.Workbooks.Open(Ruta)
DoEvents
End If
End With
Stop
'//////////////////////////////////////añadimos primero comprobación de que cada campo sea del tipo que le corresponde.
' se crean variables solo para esta comprobación y no se usarán más
Dim HayDatosMal As Boolean
Dim WKErrores As Worksheet
Dim KK As Long
KK = 3
HayDatosMal = False
For j = 0 To UBound(MatrizHojas) - 1 Step 1
Set WKSource = Nothing
Set WKSource = WBSource.Worksheets(CByte(MatrizHojas(j))) 'la posición de la hoja
LR = WKSource.Range("A" & WKSource.Rows.Count).End(xlUp).Row
Dim ZZ As Long
For ZZ = 12 To 3 Step -1
Select Case ZZ
Case 3, 4, 9, 10 'son campos de fechas
For i = 2 To LR Step 1
If IsDate(WKSource.Cells(i, ThisWorkbook.Worksheets("PANEL CONTROL").Range("C" & ZZ).Value)) = False And WKSource.Cells(i, ThisWorkbook.Worksheets("PANEL CONTROL").Range("C" & ZZ).Value) <> "" Then
HayDatosMal = True
If WKErrores Is Nothing Then Set WKErrores = Application.Workbooks.Add.ActiveSheet
With WKErrores
.Range("A1").Value = "INFORME DE ERRORES ENCONTRADOS"
.Range("A3").Value = "HOJA"
.Range("B3").Value = "FILA"
.Range("C3").Value = "CAMPO"
KK = KK + 1
.Range("A" & KK).Value = UCase(WKSource.Name)
.Range("B" & KK).Value = i
.Range("C" & KK).Value = UCase(ThisWorkbook.Worksheets("PANEL CONTROL").Range("A" & ZZ).Value)
End With
End If
Next i
Case 5, 11 'tienen que ser numéricos
For i = 2 To LR Step 1
If IsNumeric(WKSource.Cells(i, ThisWorkbook.Worksheets("PANEL CONTROL").Range("C" & ZZ).Value)) = False And WKSource.Cells(i, ThisWorkbook.Worksheets("PANEL CONTROL").Range("C" & ZZ).Value) <> "" Then
HayDatosMal = True
If WKErrores Is Nothing Then Set WKErrores = Application.Workbooks.Add.ActiveSheet
With WKErrores
.Range("A1").Value = "INFORME DE ERRORES ENCONTRADOS"
.Range("A3").Value = "HOJA"
.Range("B3").Value = "FILA"
.Range("C3").Value = "CAMPO"
KK = KK + 1
.Range("A" & KK).Value = UCase(WKSource.Name)
.Range("B" & KK).Value = i
.Range("C" & KK).Value = UCase(ThisWorkbook.Worksheets("PANEL CONTROL").Range("A" & ZZ).Value)
End With
End If
Next i
Case Else 'son textos o están vacíos, no hacemos nada
DoEvents
End Select
Next ZZ
Next j
If HayDatosMal = True Then
'hay que abortar proceso
WBSource.Close False
WKErrores.Activate
WKErrores.Columns("A:C").EntireColumn.AutoFit
Set WKErrores = Nothing
MsgBox "Se cancela el proceso porque se han encontrado errores en los datos de origen. Se ha generado un informe de errores para consultar.", vbCritical, "PROCESO CANCELADO"
GoTo Final
End If
DoEvents
'////////////////////// fin comprobación
'compruebo que los campos coincida con mis datos del configurador
MatrizCampos = ThisWorkbook.Worksheets("PANEL CONTROL").Range("A2").CurrentRegion.Value
'compruebo todas las hojas
For j = 0 To UBound(MatrizHojas) - 1 Step 1
Set WKSource = Nothing
Set WKSource = WBSource.Worksheets(CByte(MatrizHojas(j))) 'la posición de la hoja
With WKSource
'los campos empiezan en la fila 2 de los datos de la matriz de campos
'comprobamos que en source estén con el mismo nombre en su posición
For i = 2 To UBound(MatrizCampos) Step 1
If MiF.CountIf(.Rows(1), MatrizCampos(i, 1)) = 0 Then
'el campo no está presente. Abortamos
MsgBox "El campo " & UCase(MatrizCampos(i, 1)) & " no está en la hoja " & WKSource.Index & " de COST AND INCOMES", vbCritical, "PROCESO ABORTADO"
WBSource.Close False
GoTo Final
Else
'compruebo que esté en su posición
LR = MiF.Match(MatrizCampos(i, 1), .Rows(1), 0)
If LR <> MatrizCampos(i, 3) Then
'no está donde marca el PANEL CONTROL
MsgBox "El campo " & UCase(MatrizCampos(i, 1)) & " no está en la posición que marca PANEL CONTROL en la hoja " & WKSource.Index & " de COST AND INCOMES", vbCritical, "PROCESO ABORTADO"
WBSource.Close False
GoTo Final
End If
End If
Next i
End With
Next j
Set WKSource = Nothing
'también comprobamos los campos de ingresos
MatrizCampos = ThisWorkbook.Worksheets("PANEL CONTROL").Range("A8").CurrentRegion.Value
'compruebo todas las hojas
For j = 0 To UBound(MatrizHojas) - 1 Step 1
Set WKSource = Nothing
Set WKSource = WBSource.Worksheets(CByte(MatrizHojas(j))) 'la posición de la hoja
With WKSource
'los campos empiezan en la fila 2 de los datos de la matriz de campos
'comprobamos que en source estén con el mismo nombre en su posición
For i = 2 To UBound(MatrizCampos) Step 1
If MiF.CountIf(.Rows(1), MatrizCampos(i, 1)) = 0 Then
'el campo no está presente. Abortamos
MsgBox "El campo " & UCase(MatrizCampos(i, 1)) & " no está en la hoja " & WKSource.Index & " de COST AND INCOMES", vbCritical, "PROCESO ABORTADO"
WBSource.Close False
GoTo Final
Else
'compruebo que esté en su posición
LR = MiF.Match(MatrizCampos(i, 1), .Rows(1), 0)
If LR <> MatrizCampos(i, 3) Then
'no está donde marca el PANEL CONTROL
MsgBox "El campo " & UCase(MatrizCampos(i, 1)) & " no está en la posición que marca PANEL CONTROL en la hoja " & WKSource.Index & " de COST AND INCOMES", vbCritical, "PROCESO ABORTADO"
WBSource.Close False
GoTo Final
End If
End If
Next i
End With
Next j
Set WKSource = Nothing
MatrizCampos = ThisWorkbook.Worksheets("PANEL CONTROL").Range("A2").CurrentRegion.Value
'the code never reachs this part when it crashes
EstasHojas is just a string that contains text like 1|2|
I've read this but could not find a solution.
VBA force closes Excel 365 but works fine in Excel 2019
64-bit Excel 365 crashes, 32-bit Excel 365 works fine
Also tried adding DoEvents right after opening the workbook with no luck.
No add-ins involved at all.
Now comes the funny part. If I add a Stop command right after opening the first workbook, and then VBa stops there, I press F5 so macro keeps going, everything works perfect!
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Seleccione archivo COST AND INCOMES"
.AllowMultiSelect = False
If .Show = False Then
MsgBox "No se ha seleccionado ningún archivo.", vbCritical, "PROCESO ABORTADO"
GoTo Final
Else
Ruta = .SelectedItems(1)
Set WBSource = Application.Workbooks.Open(Ruta)
DoEvents
End If
End With
Stop 'this fixes everything
So if I try to execute all at once, it crashed with no errors. But if I force it to make a break and then continue, it works.
I would like to know why adding the Stop makes the code works perfectly on Eccel 365 but without it it crashed and closes Excel with no errors. Tried DoEvents as I said, but it did not help in this case.
By the way, the workbooks opened are just data in XLSX files, no other macros or events. Just this code. I can post the full code if needed but it's really long.
Thanks in advance.

Userform doesn't fill the sheet I want it to

I'm new at VBA and would like to ask for help.
I have a userform that is supposed to help me fill a range in my worksheet.
It was working fine when I made it a few days ago.
Now though, it only adds an empty row to my table and I don't know where to look to find the error. I've been at it for a couple of hours now..
Any help would be appreciated.
This is my code :
Private Sub CommandButton2_Click()
Dim dl As Integer
Dim list_num As Integer
Dim ligne As Integer
list_num = Me.liste_com3.ListCount - 1
If Me.liste_com3.ListCount > 0 Then 'contrôl si la liste n'est pas vide
If MsgBox("Voulez-vous enregistrer cette transaction ?", vbYesNo) = vbYes Then
For ligne = 0 To list_num
'ajouter nouvelle ligne dans le tableau
Sheets(8).ListObjects(1).ListRows.Add
'chercher numéro prochaine ligne du tableau
dl = Sheets(8).Range("b9999").End(xlUp).Row
'ajouter les infos dans la bdd
Sheets(8).Range("Z" & dl) = Me.info1
Sheets(8).Range("C" & dl) = Format(Me.txt_fac3, """FAC-""00000")
Sheets(8).Range("D" & dl) = Format(CDate(Now()), "dd/mm/yyyy hh:mm:ss")
Sheets(8).Range("E" & dl) = Me.cbx_com
'controler si c'est un fournisseur ou un client
If Me.label_type = "Fournisseur :" Then
Sheets(8).Range("F" & dl) = Me.cbx_type3
Else
Sheets(8).Range("G" & dl) = Me.cbx_type3
End If
'ajouter les données de la zone de liste
Sheets(8).Range("H" & dl) = Me.liste_com3.List(ligne, 0)
Sheets(8).Range("J" & dl) = Int(Me.liste_com3.List(ligne, 1))
Next ligne
MsgBox "Enregistrement réussi !"
Unload Me
ThisWorkbook.Save
End If
End If
Sheets(8).Range("K6:N9999").NumberFormat = "#,##0 [$XOF]"
End Sub
Private Sub liste_com3_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
If Me.liste_com3.ListIndex >= 0 Then
If MsgBox("Voulez-vous supprimer cette entrée ?", vbYesNo) = vbYes Then
Me.liste_com3.RemoveItem Me.liste_com3.ListIndex
memo = memo - 1
End If
End If
End Sub
Private Sub opt_in_Click()
Me.label_type = "Fournisseur :"
Me.cbx_type3.RowSource = "col_fourni"
Me.cbx_com.RowSource = "col_comm"
Me.info1 = "Entrée"
End Sub
Private Sub opt_out_Click()
Me.label_type = "Client :"
Me.cbx_type3.RowSource = "col_clients"
Me.cbx_com.RowSource = ""
Me.info1 = "Sortie"
End Sub
Private Sub txt_fac3_Change()
If Not IsNumeric(txt_fac3) And txt_fac3 <> "" Then
MsgBox "Veuillez entrer un nombre..."
Me.txt_fac3 = ""
End If
End Sub
Private Sub txt_num3_Change()
'controle si numérique
If Not IsNumeric(txt_num3) And txt_num3 <> "" Then
MsgBox "Veuillez entrer un nombre..."
Me.txt_num3 = ""
End If
End Sub
Private Sub UserForm_Initialize()
Me.label_info_3.Caption = "Mouvements"
End Sub
Also the weird thing is that when I change the sheet that the userform is supposed to write to, it works. But not on the sheet I want.
This is a picture of my userform
Thanks in advance !

How to create a hyperlink with a userform ? VBA

I have create with many help a code who create with a user form a new sheet with the name of the client and many other information. And in the first page who resume all name client i have made an hyperlink (column C) who send to queue name of the client. But with the userform a error 424 appears.
Private Sub btnajoutclient_Click()
Dim numFeuilClient As String
Dim prenomFeuilClient As String
Dim telFeuilClient As String
Dim mailFeuilClient As String
Dim AdresseFeuilClient As String
Dim cpFeuilClient As String
Dim villeFeuilClient As String
'RENDRE LES FEUILLES VISIBLES'
Worksheets(2).Visible = True
Worksheets(3).Visible = True
'CREER 2 BOITES POUR AVOIR LES INFOS : NOM ET TEL'
numFeuilClient = frmnouveauclient.TextBoxcasenom
prenomFeuilClient = frmnouveauclient.TextBoxprénom
telFeuilClient = frmnouveauclient.TextBoxcasenumérotel
mailFeuilClient = frmnouveauclient.TextBoxcasemail
AdresseFeuilClient = frmnouveauclient.TextBoxcaseadresse
cpFeuilClient = frmnouveauclient.TextBoxcasecodepostal
villeFeuilClient = frmnouveauclient.TextBoxcaseville
'freezer lécran
Application.ScreenUpdating = False
'SI PAS DE NOM SAISIE ALORS EXIT'
If numFeuilClient = "" Then
Worksheets(2).Visible = False
Worksheets(3).Visible = False
Exit Sub
End If
'ON SUPPRIME LA ZONE SELECTIONNER LA FEUILLE TYPE'
Sheets("FeuilClient").Range("_zonesuprfinal").ClearContents
Sheets("FeuilClient").Copy after:=Sheets(Sheets.Count)
'RENOMMER LA FEUILLE
ActiveSheet.Name = numFeuilClient
'ON MET LE NOM ET LE TEL DANS LES CASES SELECTIONEE DE LA FEUILLE CLIENT'
ActiveSheet.Range("_nomclient").Value = numFeuilClient
ActiveSheet.Range("_telclient").Value = telFeuilClient
ActiveSheet.Range("_prenomclient").Value = prenomFeuilClient
ActiveSheet.Range("_mailclient").Value = mailFeuilClient
ActiveSheet.Range("_adresse").Value = AdresseFeuilClient
ActiveSheet.Range("_codepostal").Value = cpFeuilClient
ActiveSheet.Range("_ville").Value = villeFeuilClient
'Aller sur la feuille fichier client
Sheets(1).Activate
'On trouve une case vide et y met le nom sur le fichier client
Feuil3.Range("A1048000").Select
ActiveCell.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = numFeuilClient
'On trouve une case vide et y met le nom sur le tel du client
Sheets("FichierClient").Range("B1048000").Select
ActiveCell.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = telFeuilClient
'Mettre un hyperlien sur le fichierclient
Sheets("FichierClient").Range("C1048000").Select
ActiveCell.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
Hyperlinks.Add Anchor:=ActiveCell, Address:="", _
SubAddress:="'" & numFeuilClient & "'!A1", TextToDisplay:="Voir Client"
'ON REND INSIVIBLE LES FEUILLES'
Worksheets(2).Visible = False
Worksheets(3).Visible = False
'défreezer l'écran
Application.ScreenUpdating = True
End Sub
Hyperlinks needs to be qualified to a Worksheet
The simple fix is change it to
ActiveSheet.HyperLinks.Add ...
That said, there is a lot of opportunity to improve this code. Consider this
Private Sub btnajoutclient_Click()
Dim numFeuilClient As String
Dim prenomFeuilClient As String
Dim telFeuilClient As String
Dim mailFeuilClient As String
Dim AdresseFeuilClient As String
Dim cpFeuilClient As String
Dim villeFeuilClient As String
Dim wsFeuilClient As Worksheet
With ThisWorkbook ' or ActiveWorkbook or specify a workbook
'RENDRE LES FEUILLES VISIBLES'
.Worksheets(2).Visible = True
.Worksheets(3).Visible = True
'CREER 2 BOITES POUR AVOIR LES INFOS : NOM ET TEL'
With frmnouveauclient
numFeuilClient = .TextBoxcasenom
'SI PAS DE NOM SAISIE ALORS EXIT'
If numFeuilClient = vbNullString Then
GoTo CleanUp
End If
prenomFeuilClient = .TextBoxprénom
telFeuilClient = .TextBoxcasenumérotel
mailFeuilClient = .TextBoxcasemail
AdresseFeuilClient = .TextBoxcaseadresse
cpFeuilClient = .TextBoxcasecodepostal
villeFeuilClient = .TextBoxcaseville
End With
'freezer lécran
Application.ScreenUpdating = False
'ON SUPPRIME LA ZONE SELECTIONNER LA FEUILLE TYPE'
.Worksheets("FeuilClient").Range("_zonesuprfinal").ClearContents
Set wsFeuilClient = .Worksheets("FeuilClient").Copy(after:=.Sheets(.Sheets.Count))
'RENOMMER LA FEUILLE
With wsFeuilClient
.Name = numFeuilClient
'ON MET LE NOM ET LE TEL DANS LES CASES SELECTIONEE DE LA FEUILLE CLIENT'
.Range("_nomclient").Value = numFeuilClient
.Range("_telclient").Value = telFeuilClient
.Range("_prenomclient").Value = prenomFeuilClient
.Range("_mailclient").Value = mailFeuilClient
.Range("_adresse").Value = AdresseFeuilClient
.Range("_codepostal").Value = cpFeuilClient
.Range("_ville").Value = villeFeuilClient
End With
'Aller sur la feuille fichier client
With .Sheets(1)
'On trouve une case vide et y met le nom sur le fichier client
.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = numFeuilClient
End With
With .Worksheets("FichierClient")
'On trouve une case vide et y met le nom sur le tel du client
.Cells(.Rows.Count, 2).End(xlUp).Offset(1, 0).Value = numFeuilClient
'Mettre un hyperlien sur le fichierclient
With .Cells(.Rows.Count, 3).End(xlUp).Offset(1, 0)
.Value = numFeuilClient
.Worksheet.Hyperlinks.Add Anchor:=.Cells, Address:=vbNullString, _
SubAddress:="'" & numFeuilClient & "'!A1", TextToDisplay:="Voir Client"
End With
End With
CleanUp:
'ON REND INSIVIBLE LES FEUILLES'
.Worksheets(2).Visible = False
.Worksheets(3).Visible = False
End With
'défreezer l'écran
Application.ScreenUpdating = True
End Sub

Error in updating UDF in Excel in non active sheets

I have created some UDF to automate some calculus me and some coworkers use regularly.
For the sake of simplicity I paste a MWE of what I have a problem with, my actual code is longer, but takes the same input, a range of cells with one of the dimensions being equal to one (so one line or one column)
Public Function Test(Donnees As Range)
Dim Nombre_Cellules, Temp As Double
Dim Format_Donnees As String
Temp = 0
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' '
' Parametres utiles generaux '
' '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Nb_Lignes = Donnees.Rows.Count
Nb_Colonnes = Donnees.Columns.Count
Premiere_Ligne = Donnees.Row
Premiere_Colonne = Donnees.Column
Derniere_Ligne = Donnees.Row + Nb_Lignes - 1
Derniere_Colonne = Donnees.Column + Nb_Colonnes - 1
'On definit la frequence et la taille associee
If Nb_Lignes = 1 Then
Format_Donnees = "Colonnes"
Nombre_Cellules = Nb_Colonnes
End If
If Nb_Colonnes = 1 Then
Format_Donnees = "Lignes"
Nombre_Cellules = Nb_Lignes
End If
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' '
' Verifications des parametres et messages d'erreurs '
' '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'On verifie que la plage renseignée est soit sur une seule ligne soit sur une seule colonne
If (Nb_Lignes <> 1 And Nb_Colonnes <> 1) Then
MsgBox _
"La plage de données considérée est incorrecte, il ne peut s'agir que " & vbNewLine & _
Chr(149) & " de données sur une seule ligne ou " & vbNewLine & _
Chr(149) & " de données sur une seule colonne" _
, , "Parametres incorrects"
Test = CVErr(xlErrRef)
Exit Function
End If
'On verifie que toute la période qui sert au calcul contient bien des valeurs numériques et ne contient pas de valeurs vides
If Format_Donnees = "Lignes" Then
For i = 0 To Nombre_Cellules - 1
If Not IsNumeric(Cells(Premiere_Ligne + i, Premiere_Colonne).Value) Then
MsgBox _
"La plage de donnée considérée est incorrecte" & vbNewLine & _
"Toutes les cellules nécessaires au calcul dans la colonne ne sont pas numériques" _
, , "Parametres incorrects"
Test = CVErr(xlErrRef)
Exit Function
End If
If (Cells(Premiere_Ligne + i, Premiere_Colonne).Value = "") Then
MsgBox _
"La plage de donnée considérée est incorrecte" & vbNewLine & _
"Une cellule de la colonne considérée est vide et semble avoir une valeur manquante" _
, , "Parametres incorrects"
Test = CVErr(xlErrRef)
Exit Function
End If
Next
End If
If Format_Donnees = "Colonnes" Then
For i = 0 To Nombre_Cellules - 1
If Not IsNumeric(Cells(Premiere_Ligne, Premiere_Colonne + i).Value) Then
MsgBox _
"La plage de donnée considérée est incorrecte" & vbNewLine & _
"Toutes les cellules nécessaires au calcul dans la ligne ne sont pas numériques" _
, , "Parametres incorrects"
Test = CVErr(xlErrRef)
Exit Function
End If
If (Cells(Premiere_Ligne, Premiere_Colonne + i).Value = "") Then
MsgBox _
"La plage de donnée considérée est incorrecte" & vbNewLine & _
"Une cellule de la ligne considérée est vide et semble avoir une valeur manquante" _
, , "Parametres incorrects"
Test = CVErr(xlErrRef)
Exit Function
End If
Next
End If
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' '
' Calculs a proprement parler '
' '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Format_Donnees = "Lignes" Then
For i = 0 To Nombre_Cellules - 1
Temp = Temp + Cells(Premiere_Ligne + i, Premiere_Colonne).Value
Next
End If
If Format_Donnees = "Colonnes" Then
For i = 0 To Nombre_Cellules - 1
Temp = Temp + Cells(Premiere_Ligne, Premiere_Colonne + i).Value
Next
End If
Test = Temp
End Function
So as I will not be the sole user of this function, I have tried to include several checks and error messages.
One is to check if the range selected has any empty values and any non numerical value.
Now my functions work (at least they calculate the thing I want them to), but I have some troubles with how they update.
Note that I have pushed against user preferences so that all the value used are included in the range passed in input.
One of the issues I have been able to reproduce with this code is that If I use this function on several sheets of one workbook (so one Test() in worksheet1, and one Test() in worksheet2, and for one reason try to update the whole workbook (e.g. via Ctrl + alt + shift + F9), then I will get one warning I have set up ("Une cellule de la ligne considérée est vide et semble avoir une valeur manquante") in a non active sheet.
Can someone explain me one ?
You are using Cells() with no sheet qualification. This means that it refers to whatever the active sheet happens to be. So it won't work correctly unless all the calls to your UDF are on the currently active sheet
You need to change this to Donnees.Cells( ) and change the Cell indexes to refer to the cells within Donnees rather than cells within the whole sheet

Excel VBA : Code to protect template and remain protected after copying

I have a template which represents a data table for the days of the week, I want to protect the template for modification (I done that), and when I press the button "Insert a new sheet for the next week", I get a copy of the template but it's not protected like the template.
How can I do That ?
There is my code :
Sub Bouton_NewSheet()
Dim NumSemaine As String
NumSemaine = InputBox("Veuillez entrer le numéro de la semaine :", "Insertion d'une feuille vierge")
If NumSemaine <> "" Then
'vérifier si valeur nuémrique
While Not IsNumeric(NumSemaine)
MsgBox "Merci de saisir une valeur numérique", vbExclamation
NumSemaine = InputBox("Veuillez entrer un numéro de semaine", "Insertion d'une feuille vierge")
Wend
Sheets("Template").Visible = True
Sheets("Template").Copy After:=Sheets(Worksheets.Count)
ActiveSheet.Name = "S" & NumSemaine
ActiveSheet.Range("B1").Value = "S" & NumSemaine
Sheets("Template").Visible = True
MsgBox "Votre feuille de suivi de stock est pour la semaine N°" & NumSemaine
End If
Sheets("Template").Protect
End Sub
Thank you

Resources