VBA Macro TO Export Splines from catia to text file(.dat) - vba

so I was wondering if i could get some help here. so basically i am trying to find out how to write a dat file that will be able to import splines into Catia. These splines when imported are supposed to act like meshes on a structure, that is, picture a meshed structure, but instead of mesh it will be splines on it. so right now i thought to learn a macro that exports a few splines i created on a structure into a text(.dat) file. but i have been having troubles with the macro i have as it asks me to select a spline, but wont allow me to click on the spline in spec tree. The thing is that i have lots of splines and i would like the macro to just select splines automatically without asking and export them..... PLS HELP ME. thanks alot.
So here is the code:
Sub CATMain()
'*** *** Definition Variables
Dim CtrlPoint()
Dim oCoordinates(1)
Dim StartKrit As Integer
'*** Query document type ***
StartKrit = 0
Set oDoc = CATIA.ActiveDocument
ObjType = TypeName(oDoc)
If ObjType = "PartDocument" Then
DocType = "Part"
StartKrit = 1
ElseIf ObjType = "DrawingDocument" Then
DocType = "Drawing "
StartKrit = 1
End If
If StartKrit = 0 Then
box = MsgBox(" The active document is neither a CATPart still CATDrawing! " + Chr(10) + _
" The macro can not continue and will now exit " + Chr(10) + _
"Please select a CATPart or a CATDrawing and start the macro again!", vbCritical + vbOKOnly, "incorrect document type")
Exit Sub
End If
'*** Create the * .txt files ***
StorePath = "C: \"
StoreName = "Splinekoordinaten" & Date
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FileExists(StorePath & StoreName & ".txt ") = True Then
box = MsgBox(" file ==> " + StorePath + StoreName + " <== already exists! " + Chr(10) + " Do you want to overwrite the file? ", vbCritical + vbYesNo, "file already exists ")
If box = vbNo Then
box = MsgBox(" The macro is now finished ", vbInformation + vbOKOnly, " the user stops ")
Exit Sub
End If
End If
Set A = fs.CreateTextFile("D:\school\INTERNSHIP\Macro\Newest.txt ", True)
A.WriteLine (" points coordinates of a spline ")
A.WriteLine (" ")
If DocType = " Part " Then
A.WriteLine (" name of CATParts: " & oDoc.Name)
ElseIf DocType = " Drawing " Then
A.WriteLine ("name of CATDrawing:" & oDoc.Name)
End If
A.WriteLine ("")
'*** Readout from the CATDrawing ***
If DocType = "Drawing" Then
Dim otype2D(0)
Dim Selection
Set mysel = oDoc.Selection
mysel.Clear
otype2D(0) = "Spline2D"
mysel.Clear
box = MsgBox(" Please select now the spline ", vbInformation + vbOKCancel, " spline Select ")
If box = vbCancel Then
box = MsgBox(" you have the selection canceled " + Chr(10) + _
" the macro is now finished! ", vbCritical, "abort by user")
If fs.FileExists(StorePath & StoreName & ".txt") = True Then
A.Close
fs.DeleteFile (StorePath & StoreName & ".txt")
End If
Exit Sub
End If
Selection = mysel.SelectElement2(otype2D, "Please select the spline", False)
If Selection = "Normal" Then
oSplineName = mysel.Item(1).Value.Name
Set oSpline = mysel.Item(1).Value
A.WriteLine ("name of the selected spline:" & oSplineName)
A.WriteLine ("")
A.WriteLine ("")
Else
box = MsgBox("you have canceled the selection" + Chr(10) + _
"the macro is now finished! ", vbCritical, " abort by user ")
If fs.FileExists(StorePath & StoreName & " .txt ") = True Then
A.Close
fs.DeleteFile (StorePath & StoreName & " .txt ")
End If
Exit Sub
End If
mysel.Clear
Set QuCtrlP = oSpline.EndPoint
QuCtrlPRaw = QuCtrlP.Name
QuCtrlPSemi = Split(QuCtrlPRaw, ".")
QuCtrlPFin = QuCtrlPSemi(1) - 1
ReDim Preserve CtrlPoint(QuCtrlPFin)
For j = 0 To QuCtrlPFin
Set CtrlPoint(j) = oSpline.GetItem("Ktrl-point." & j + 1)
CtrlPoint(j).GetCoordinates oCoordinates
A.WriteLine ("point" & j + 1 & "X / Y")
A.WriteLine (oCoordinates(0))
A.WriteLine (oCoordinates(1))
A.WriteLine ("")
Next
'*** readout from the CATPart ***
ElseIf DocType = "Part" Then
Dim otype3D(0)
Set mysel = oDoc.Selection
mysel.Clear
otype3D(0) = "Spline2D"
mysel.Clear
box = MsgBox("Please select now the spline", vbInformation + vbOKCancel, "spline Select")
If box = vbCancel Then
box = MsgBox("you have canceled the selection" + Chr(10) + _
"The macro is now finished!", vbCritical, "abort by user")
If fs.FileExists(StorePath & StoreName & ".txt") = True Then
A.Close
fs.DeleteFile (StorePath & StoreName & ".txt ")
End If
Exit Sub
End If
Selection = mysel.SelectElement2(otype3D, " Please select the spline ", False)
If Selection = " Normal " Then
oSplineName = mysel.Item(1).Value.Name
Set oSpline = mysel.Item(1).Value
A.WriteLine ("name of the selected spline:" & oSplineName)
A.WriteLine ("")
A.WriteLine ("")
Else
box = MsgBox("you have canceled the selection" + Chr(10) + _
"The macro is now finished!", vbCritical, "abort by user")
If fs.FileExists(StorePath & StoreName & ".txt") = True Then
A.Close
fs.DeleteFile (StorePath & StoreName & " .txt ")
End If
Exit Sub
End If
mysel.Clear
Set QuCtrlP = oSpline.EndPoint
QuCtrlPRaw = QuCtrlP.Name
QuCtrlPSemi = Split(QuCtrlPRaw, " ")
QuCtrlPFin = QuCtrlPSemi(1) - 1
ReDim Preserve CtrlPoint(QuCtrlPFin)
For j = 0 To QuCtrlPFin
Set CtrlPoint(j) = oSpline.GetItem("Ktrl-point." & j + 1)
CtrlPoint(j).GetCoordinates oCoordinates
A.WriteLine ("point" & j + 1 & "X / Y")
A.WriteLine (oCoordinates(0))
A.WriteLine (oCoordinates(1))
A.WriteLine ("")
Next
End If
'**** Issue Storage Location ****
Ml = "The macro has completed successfully"
M2 = "The * .txt file is saved under the following path:"
M2_ZU_1 = "==>"
M2_ZU_2 = "<== "
M3 = " Are you in the path now oeffnen? "
Title = "memory data"
skin = vbInformation + vbYesNo
query = MsgBox(Ml + Chr(10) + Chr(10) + M2 + Chr(10) + Chr(10) + M2_ZU_1 + StorePath + StoreName + M2_ZU_2 + Chr(10) + Chr(10) + M3, skin, Title)
If query = vbYes Then
ExplorerPath = "C: \ WINDOWS \ explorer.exe"
Explorer = CATIA.SystemService.ExecuteProcessus(ExplorerPath & "" & StorePath)
End If
End Sub

Your selectelement2 filter is set for spline2D, are you selected sketch splines or 3d splines?
If you are working with 3d splines like it sounds, you want to use this code:
mysel.Clear
otype3D(0) = "HybridShapeSpline"
mysel.Clear
box = MsgBox("Please select now the spline", vbInformation + vbOKCancel, "spline Select")
If box = vbCancel Then
box = MsgBox("you have canceled the selection" + Chr(10) + _
"The macro is now finished!", vbCritical, "abort by user")
If fs.FileExists(StorePath & StoreName & ".txt") = True Then
A.Close
fs.DeleteFile (StorePath & StoreName & ".txt ")
End If
Exit Sub
End If
Selection = mysel.SelectElement2(otype3D, " Please select the spline ", False)
You'll find more help on www.coe.org, there is a significant group of CATIA automators there.

Related

Checking Null Value in Access VBA recordset throws null exception?

I have tried this every different way, and it was working yesterday, so I really don't know what changed.
I import a spreadsheet to a temp table in an Access app. Then I set that to be the dao.recordset, and start looping through. I check for the ID to not be null and if not go through checking fields for values, and updating as appropriate. the minute I hit a null, I get a system error "94 - invalid use of null"
It doesn't offer a debug, but I have debugs throughout my code, so I can see where it fails. It fails when I do this check: If IsNull(rstImportCList("columnx")) = False Then
I have tried nz(rstImportCList("columnx"),"") <> "" I have tried rstImportCList("columnx") is not null, and everything else I can think of. Why is the check that is supposed to prevent this error, causing this error?
Edit:
This is the beginning where I declare the recordset I can't get past doing anything with the recordset field.
Dim db As DAO.Database
Dim rstImportCList As DAO.Recordset
Dim RSsql As String
Set db = CurrentDb()
RSsql = "Select * from tblTempImportCList"
Set rstImportCList = db.OpenRecordset(RSsql)
If rstImportCList.EOF Then Exit Sub
Do While Not rstImportCList.EOF
whether I try to check
IsNull(rstImportCList("xyz").Value) = False
or
nz(rstImportCList("xyz").Value,"") <> ""
or
dim x as string
x = rstImportCList!xyz.value
I get the same error 94 invalid use of null.
Any idea why this is?
--edit with more code.
I took some time to take a the beginning and some of each section of the code, so I could make it generic and see if anyone can help. Here is what I am working on. The Code1 and Code2 parts don't seem to be the issue. Sometimes it fails on a null value in a Yes/No column (I'm just looking for Y but the value is null), sometimes on the notes being null. It's not consistent, which is why I'm having a hard time nailing down the issue.
Private Sub cmdImportList_Click()
On Error GoTo cmdImportExcel_Click_err:
Dim fdObj As FileDialog
Set fdObj = Application.FileDialog(msoFileDialogFilePicker)
Dim varfile As Variant
Dim importCT As Integer
Dim dbu As DAO.Database
Dim cBadXVal, cBadYVal As Integer
Dim preNotes As String
Dim RSsql As String
Dim uNotesql, uVal1sql, uVal2sql As String
Dim db As DAO.Database
Dim rstImportCList As DAO.Recordset
Dim CheckB4Import As Integer
CheckB4Import = MsgBox("Are you SURE the sheet you are importing has the following column names in the same order:" & vbCrLf & vbCrLf & _
"IDName/ First/ Mid/ Last/ Sfx/ Age/ Telephone/ Code1/ Code2/ YN1/ YN2/ NY3/ Notes/ AsYN1edTo" & vbCrLf & vbCrLf & _
"AND that there are NO empty rows or empty columns?" & vbCrLf & vbCrLf & _
"Click OK to proceed, Click CANCEL to go double-check your CallSheet before importing.", vbOKCancel, "WITH GREAT POWER COMES GREAT RESPONSIBILITY TO QC DATA")
If CheckB4Import = vbOK Then
CurrentDb.Execute "DELETE * FROM tblTempImportCList", dbFailOnError
With fdObj
'CAN ONLY SELECT 1 FILE
.allowmultiselect = False
.Filters.Clear
.Filters.Add "Excel 2007+", "*.xlsx"
.Title = "Please select the completed list to import:"
.Show
If .SelectedItems.Count = 1 Then
varfile = .SelectedItems(1)
DoCmd.TransferSpreadsheet acImport, , "tblTempImportCList", varfile, True, "Sheet1!"
cBadXVal = DLookup("BadXCount", "qryImpCheckBadXVal")
Debug.Print "cBadXVal - " & cBadXVal
If cBadXVal <> 0 Then
DoCmd.OpenForm "frmImportError", acNormal
Forms!frmImportError.Form.lblErrorMsg.Caption = _
"Oh No! Your list import failed!" & vbCrLf & _
cBadXVal & " X values are not valid." & vbCrLf & _
"Don't worry. You can fix your sheet and re-import!" & vbCrLf & _
"Would you like to open the documentation for the valid codes" & vbCrLf & _
"Or are you all set?"
End If
cBadYVal = DLookup("BadYCount", "qryImpCheckBadYVal")
Debug.Print "cBadYVal - " & cBadYVal
If cBadYVal <> 0 Then
DoCmd.OpenForm "frmImportError", acNormal
Forms!frmImportError.Form.lblErrorMsg.Caption = _
"Oh No! Your list import failed!" & vbCrLf & _
cBadYVal & " YN1 values are not valid." & vbCrLf & _
"Don't worry. You can fix your sheet and re-import!" & vbCrLf & _
"Would you like to open the documentation for the valid codes" & vbCrLf & _
"Or are you all set?"
Exit Sub
End If
Else
MsgBox "No file was selected. Try again!", vbCritical, "Uh-oh Spaghettios!"
End If
End With
'PASSED CHECKS
Set db = CurrentDb()
RSsql = "Select * from tblTempImportCList"
Set rstImportCList = db.OpenRecordset(RSsql)
If rstImportCList.EOF Then Exit Sub
Debug.Print "got here"
Do While Not rstImportCList.EOF
Debug.Print "Start Processing: " & Nz(rstImportCList("IDName").Value, "")
'GET NOTES ALREADY ON RECORD
If Nz(rstImportCList("IDName").Value, "") <> "" Then
Debug.Print "got past if IDName is not null"
If Nz(rstImportCList("Notes").Value, "") <> "" Then
Debug.Print "got past if notes is not null"
preNotes = Replace(Nz(DLookup("Notes", "tblVFileImport", "IDName = " & rstImportCList("IDName").Value), ""), """", "")
'UPDATE NOTES
If Nz(preNotes, "") <> "" Then
uNotesql = "Update tblVFileImport SET tblVFileImport.Notes = '" & preNotes & "; " & Replace(Nz(rstImportCList("Notes").Value, ""), """", "") & "' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName").Value
'debug.print "Notes"
'debug.print "uNotesql - " & uNotesql
Else
uNotesql = "Update tblVFileImport SET tblVFileImport.Notes = '" & Replace(Nz(rstImportCList("Notes").Value, ""), """", "") & "' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName").Value
End If
RunMySql (uNotesql)
'DoCmd.RunSQL (uNotesql), dbFailOnError
End If
If Nz(rstImportCList("YN1").Value, "") = "Y" Then
'UPDATE YN1
uYN1sql = "Update tblVFileImport SET tblVFileImport.YN1 = '" & rstImportCList("YN1") & "', tblVFileImport.callprocessed = 'Y' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "YN1 = Y or y"
Debug.Print "uYN1sql - " & uYN1sql
RunMySql (uYN1sql)
'DoCmd.RunSQL (uYN1sql), dbFailOnError
End If
If Nz(rstImportCList("YN2").Value, "") = "Y" Then
'UPDATE YN2
uYN2sql = "Update tblVFileImport SET tblVFileImport.YN2 = '" & rstImportCList("YN2") & "', tblVFileImport.callprocessed = 'Y' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "YN2 = Y or y"
Debug.Print "uYN2sql - " & uYN2sql
RunMySql (uYN2sql)
'DoCmd.RunSQL (uYN2sql), dbFailOnError
End If
'START Code1 PROCESSING
If Nz(rstImportCList("Code1").Value, "") <> "" Then
'Code1 Case abc
vdispo = DLookup("Code1", "tblvFileImport", "IDName = " & rstImportCList("IDName"))
If rstImportCList("Code1") = "ABC" Then
Debug.Print "Dispo Case ABC"
'DELETE RECORD
dMDsql = "DELETE from tblVFileImport " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "dMDsql - " & dMDsql
RunMySql (dMDsql)
'DoCmd.RunSQL (dMDsql), dbFailOnError
'Code1 Case DEF OR GHI OR JKL
ElseIf Nz(rstImportCList("Code1"), "") = "DEF" Or Nz(rstImportCList("Code1"), "") = "GHI" Or Nz(rstImportCList("Code1"), "") = "JKL" Then
Debug.Print "Dispo Case DEF OR GHI OR JKL "
'IF DEF
If rstImportCList("Code1") = "DEF" Then
'IF CELL SAME - UPDATE NULL
ccellsame = DLookup("IDName", "tblVFileImport", "IDName = " & rstImportCList("IDName") & " AND nz(Cell,'') = Phone ")
If ccellsame = rstImportCList("IDName") Then
uCellsql = "Update tblVFileImport SET tblVFileImport.Cell = NULL, tblVFileImport.CellString = NULL, tblVFileImport.mobileflag = NULL " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "uCellsql - " & uCellsql
RunMySql (uCellsql)
'DoCmd.RunSQL (uCellsql), dbFailOnError
End If
End If
End If
End If
End If
Debug.Print "End Processing: " & rstImportCList("IDName")
rstImportCList.MoveNext
Loop
Debug.Print "Finished Looping"
rstImportCList.Close
importCT = DCount("IDName", "tblTempImportCList")
MsgBox importCT & " Records imported for list.", vbOKOnly, "List Processed"
Else
MsgBox "Good Call. Check twice, import once!", vbOKOnly, "Better Safe Than Sorry"
End If
Exit Sub
cmdImportExcel_Click_err:
Select Case Err.Number
Case Else
Call MsgBox(Err.Number & " – " & Err.Description, vbCritical + vbOKOnly, "System Error …")
End Select
End Sub
Any suggestions are greatly appreciated. I'm 1/2 tempted to suck this into a SQL table and just execute a stored procedure. I can get it to work in there, I think.
If IsNull(rstImportCList("columnx").Value) Then
otherwise you're checking if the Field object itself is null.
https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/field-object-dao#:~:text=To%20refer%20to,Fields(%22name%22)
This is a case where relying on a default property (in this case Value) causes problems.

List FormatConditions of all controls on an Access form

Is it possible to list the conditional formatting of all controls on a form? I'd like to be able to list out all existing conditions so that I can generate code to add/remove the existing conditions. I have inherited some complex forms and want to know what I'm dealing with and then generate some code to toggle the conditional formatting in areas where it is slowing down navigating a continuous form.
This Excel VBA example shows a similar format I'd like to have for Access.
https://stackoverflow.com/a/52204597/1898524
Only textboxes and comboboxes have Conditional Formatting.
There is no single property that can be listed to show a control's conditional formatting rule(s). Each rule has attributes that can be listed. Example of listing for a single specific control:
Private Sub Command25_Click()
Dim x As Integer
With Me.tbxRate
For x = 0 To .FormatConditions.Count - 1
Debug.Print .FormatConditions(x).BackColor
Debug.Print .FormatConditions(x).Expression1
Debug.Print .FormatConditions(x).FontBold
Next
End With
End Sub
The output for this example:
2366701
20
False
These are attributes for a rule that sets backcolor to red when field value is greater than 20.
Yes, code can loop through controls on form, test for textbox and combobox types, determine if there are CF rules and output attributes.
With some inspiration from #June7's example and some code from an article I found by Garry Robinson, I wrote a procedure that answers my question.
Here's the output in the Immediate window. This is ready to be pasted into a module. The design time property values are shown as a comment.
txtRowColor.FormatConditions.Delete
txtRowColor.FormatConditions.Add acExpression, acBetween, "[txtCurrent_Equipment_List_ID]=[txtEquipment_List_ID]"
With txtRowColor.FormatConditions.Item(txtRowColor.FormatConditions.Count-1)
.Enabled = True ' txtRowColor.Enabled=False
.ForeColor = 0 ' txtRowColor.ForeColor=-2147483640
.BackColor = 10092543 ' txtRowColor.BackColor=11850710
End With
You can test this sub from a click event on an open form. I was getting some false positives when checking the Boolean .Enabled property, even when I store the values into Boolean variables first. I don't know why and am researching it, but that is beyond the scope of this question.
Public Sub ListConditionalFormats(frmForm As Form)
' Show all the Textbox and Combobox controls on the passed form object (assuming the form is open).
' Output the FormatCondtion properties to the immediate window in a format that is
' suitable to be copied into VBA to recreate the conditional formatting.
' The design property value is shown as a comment on each condition property row.
Dim ctl As Control
Dim i As Integer
Dim bolControlEnabled As Boolean
Dim bolFormatEnabled As Boolean
On Error GoTo ErrorHandler
For Each ctl In frmForm.Controls
If TypeOf ctl Is TextBox Or TypeOf ctl Is ComboBox Then
With ctl
If .FormatConditions.Count > 0 Then
'Debug.Print vbCr & "' " & ctl.Name, "Count = " & .FormatConditions.Count
For i = 0 To .FormatConditions.Count - 1
' Generate code that can recreate each FormatCondition
Debug.Print ctl.Name & ".FormatConditions.Delete"
Debug.Print ctl.Name & ".FormatConditions.Add " & DecodeType(.FormatConditions(i).Type) _
& ", " & DecodeOp(.FormatConditions(i).Operator) _
& ", """ & Replace(.FormatConditions(i).Expression1, """", """""") & """" _
& IIf(Len(.FormatConditions(i).Expression2) > 0, ", " & .FormatConditions(i).Expression2, "")
Debug.Print "With " & ctl.Name & ".FormatConditions.Item(" & ctl.Name & ".FormatConditions.Count-1)"
bolControlEnabled = ctl.Enabled
bolFormatEnabled = .FormatConditions(i).Enabled
'Debug.Print bolControlEnabled <> bolFormatEnabled, bolControlEnabled, bolFormatEnabled
If bolControlEnabled <> bolFormatEnabled Then ' <- This sometimes fails. BS 2/9/2020
'If ctl.Enabled <> .FormatConditions(i).Enabled Then ' <- This sometimes fails. BS 2/9/2020
Debug.Print vbTab & ".Enabled = " & .FormatConditions(i).Enabled; Tab(40); "' " & ctl.Name & ".Enabled=" & ctl.Enabled
End If
If ctl.ForeColor <> .FormatConditions(i).ForeColor Then
Debug.Print vbTab & ".ForeColor = " & .FormatConditions(i).ForeColor; Tab(40); "' " & ctl.Name & ".ForeColor=" & ctl.ForeColor
End If
If ctl.BackColor <> .FormatConditions(i).BackColor Then
Debug.Print vbTab & ".BackColor = " & .FormatConditions(i).BackColor; Tab(40); "' " & ctl.Name & ".BackColor=" & ctl.BackColor
End If
If ctl.FontBold <> .FormatConditions(i).FontBold Then
Debug.Print vbTab & ".FontBold = " & .FormatConditions(i).FontBold; Tab(40); "' " & ctl.Name & ".FontBold=" & ctl.FontBold
End If
If ctl.FontItalic <> .FormatConditions(i).FontItalic Then
Debug.Print vbTab & ".FontItalic = " & .FormatConditions(i).FontItalic; Tab(40); "' " & ctl.Name & ".FontItalic=" & ctl.FontItalic
End If
If ctl.FontUnderline <> .FormatConditions(i).FontUnderline Then
Debug.Print vbTab & ".FontUnderline = " & .FormatConditions(i).FontUnderline; Tab(40); "' " & ctl.Name & ".FontUnderline=" & ctl.FontUnderline
End If
If .FormatConditions(i).Type = 3 Then ' acDataBar
Debug.Print vbTab & ".LongestBarLimit = " & .FormatConditions(i).LongestBarLimit
Debug.Print vbTab & ".LongestBarValue = " & .FormatConditions(i).LongestBarValue
Debug.Print vbTab & ".ShortestBarLimit = " & .FormatConditions(i).ShortestBarLimit
Debug.Print vbTab & ".ShortestBarValue = " & .FormatConditions(i).ShortestBarValue
Debug.Print vbTab & ".ShowBarOnly = " & .FormatConditions(i).ShowBarOnly
End If
Debug.Print "End With" & vbCr
Next
End If
End With
End If
Next
Beep
Exit_Sub:
Exit Sub
ErrorHandler:
MsgBox "Error #" & Err.Number & " - " & Err.Description & vbCrLf & "in procedure ListConditionalFormats" _
& IIf(Erl > 0, vbCrLf & "Line #: " & Erl, "")
GoTo Exit_Sub
Resume Next
Resume
End Sub
Function DecodeType(TypeProp As Integer) As String
' You heed this are there are 4 different ways to setup a CondtionalFormat
' https://vb123.com/listing-conditional-formats
Select Case TypeProp
Case 0
DecodeType = "acFieldValue"
Case 1
DecodeType = "acExpression"
Case 2
DecodeType = "acFieldHasFocus"
Case 3
DecodeType = "acDataBar"
End Select
End Function
Function DecodeOp(OpProp As Integer) As String
' You need this becuase equations can comprise of = > <> between
' https://vb123.com/listing-conditional-formats
Select Case OpProp
Case 0
DecodeOp = "acBetween"
Case 1
DecodeOp = "acNotBetween"
Case 2
DecodeOp = "acEqual"
Case 3
DecodeOp = "acNotEqual"
Case 4
DecodeOp = "acGreaterThan"
Case 5
DecodeOp = "acLessThan"
Case 6
DecodeOp = "acGreaterThanOrEqual"
Case 7
DecodeOp = "acLessThanOrEqual"
End Select
End Function

adding page numbers when programatically merging PDFs with acrobat

Hi the code below merges pdfs using adobe acrobat. It works but I am looking to add page numbers to the document so that if I merge 2 documents that are 4 pages each the page numbers go from 1 to 8. How can that be done?
Here is the code:
'http://www.vbaexpress.com/forum/showthread.php?47310-Need-code-to-merge-PDF-files-in-a-folder-using-adobe-acrobat-X
Sub MergePDFs()
' ZVI:2013-08-27 http://www.vbaexpress.com/forum/showthread.php?47310-Need-code-to-merge-PDF-files-in-a-folder-using-adobe-acrobat-X
' Reference required: "VBE - Tools - References - Acrobat"
' --> Settings, change to suit
Const MyPath = "C:\mypath" '"C:\Temp" ' Path where PDF files are stored
Const MyFiles = "file1.pdf,file2.pdf" ' List of PDFs to ne merged
Const DestFile = "MergedFile.pdf" ' The name of the merged file
' <-- End of settings
Dim a As Variant, i As Long, n As Long, ni As Long, p As String
Dim AcroApp As New Acrobat.AcroApp, PartDocs() As Acrobat.CAcroPDDoc
If Right(MyPath, 1) = "\" Then p = MyPath Else p = MyPath & "\"
a = Split(MyFiles, ",")
ReDim PartDocs(0 To UBound(a))
On Error GoTo exit_
If Len(Dir(p & DestFile)) Then Kill p & DestFile
For i = 0 To UBound(a)
' Check PDF file presence
If Dir(p & Trim(a(i))) = "" Then
MsgBox "File not found" & vbLf & p & a(i), vbExclamation, "Canceled"
Exit For
End If
' Open PDF document
Set PartDocs(i) = CreateObject("AcroExch.PDDoc")
PartDocs(i).Open p & Trim(a(i))
If i Then
' Merge PDF to PartDocs(0) document
ni = PartDocs(i).GetNumPages()
If Not PartDocs(0).InsertPages(n - 1, PartDocs(i), 0, ni, True) Then
MsgBox "Cannot insert pages of" & vbLf & p & a(i), vbExclamation, "Canceled"
End If
' Calc the number of pages in the merged document
n = n + ni
' Release the memory
PartDocs(i).Close
Set PartDocs(i) = Nothing
Else
' Calc the number of pages in PartDocs(0) document
n = PartDocs(0).GetNumPages()
End If
Next
If i > UBound(a) Then
' Save the merged document to DestFile
If Not PartDocs(0).Save(PDSaveFull, p & DestFile) Then
MsgBox "Cannot save the resulting document" & vbLf & p & DestFile, vbExclamation, "Canceled"
End If
End If
exit_:
' Inform about error/success
If Err Then
MsgBox Err.Description, vbCritical, "Error #" & Err.Number
ElseIf i > UBound(a) Then
MsgBox "The resulting file is created:" & vbLf & p & DestFile, vbInformation, "Done"
End If
' Release the memory
If Not PartDocs(0) Is Nothing Then PartDocs(0).Close
Set PartDocs(0) = Nothing
' Quit Acrobat application
AcroApp.Exit
Set AcroApp = Nothing
End Sub
attached a stand-alone VBS/VBA script, which add the page number as footer to your pdf. You may took out the parts you need and write into your script just before you save the pdf or execute it afterwards.
Full Script:
File = "D:\Test.pdf"
Set App = CreateObject("Acroexch.app") '//start acrobat
app.show '//show Acrobat or comment out for hidden mode
Set AVDoc = CreateObject("AcroExch.AVDoc")
Set AForm = CreateObject("AFormAut.App") '//get AFormAPI to execute js later
If AVDoc.Open(File,"") Then
'//write JS-Code on a variable
Ex = " // set Date, filename and PageNo as footer "&vbLF _
& " var Box2Width = 50 "&vbLF _
& " for (var p = 0; p < this.numPages; p++) "&vbLF _
& " { "&vbLF _
& " var aRect = this.getPageBox(""Crop"",p); "&vbLF _
& " var TotWidth = aRect[2] - aRect[0] "&vbLF _
& " { var bStart=(TotWidth/2)-(Box2Width/2) "&vbLF _
& " var bEnd=((TotWidth/2)+(Box2Width/2)) "&vbLF _
& " var fp = this.addField(String(""xftPage""+p+1), ""text"", p, [bStart,30,bEnd,15]); "&vbLF _
& " fp.value = ""Page: "" + String(p+1)+ ""/"" + this.numPages; "&vbLF _
& " fp.textSize=6; fp.readonly = true; "&vbLF _
& " fp.alignment=""center""; "&vbLF _
& " } "&vbLF _
& " } "
'//Execute JS-Code
AForm.Fields.ExecuteThisJavaScript Ex
msgBox("Done")
end if
Set AVDoc = Nothing
Set APP = Nothing
The parts you really need if you only want to take over in your script:
Set AForm = CreateObject("AFormAut.App")
Ex = " // set Date, filename and PageNo as footer "&vbLF _
& " .....
& " .....
& " } "
'//Execute JS-Code
AForm.Fields.ExecuteThisJavaScript Ex
This also demonstrates how you can use/execute AcroJs via VBS/VBA without translating to JSO (Java Script Object).
Good luck, Reinhard

How to get a persons active directory groups?

I am using this asmx.VB code to authenticate a user in AD. I need to also bring back what groups they are members of. Any help would be appreciated.
<WebMethod(Description:="Checks User against Active Directory.", EnableSession:=False)> _
Public Function CHECK_AD(ByVal userid As String, ByVal Password As String) As Integer
Dim iErrorNumber As Integer
Dim isPass As Boolean = False
Try
Dim pc As New PrincipalContext(ContextType.Domain, "SomeDomain")
isPass = pc.ValidateCredentials(userid, Password, ContextOptions.Negotiate)
If isPass = True Then
iErrorNumber = 1
Else
iErrorNumber = 0
End If
Catch ex As Exception
iErrorNumber = -1
End Try
Return iErrorNumber
End Function
I Have this code to get properties of user in active directory, maybe can help you, just add a button and if you want uncomment the first three comment lines and comment the first three lines of code after declarations.
(sorry the code is in spanish).
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim objetoUsuario, gruposSeguridad
Dim ultimoInicioSesion As String
Dim dominio As String
Dim nombreUsuario As String
Dim estadoCuenta As String
Dim gruposSeguridadUsuario As String = ""
'dominio = InputBox("Nombre del dominio Windows Server", "")
dominio = Environment.UserDomainName
'nombreUsuario = InputBox("Nombre de usuario del dominio", "")
nombreUsuario = Environment.UserName
' On Error GoTo cError
On Error Resume Next
objetoUsuario = GetObject("WinNT://" + dominio + "/" + nombreUsuario + ",user")
If Err.Number = 0 Then
If objetoUsuario.AccountDisabled = True Then
estadoCuenta = "Deshabilitado"
ultimoInicioSesion = "No existe"
Else
estadoCuenta = "Habilitado"
ultimoInicioSesion = objetoUsuario.Get("Lastlogin")
End If
gruposSeguridad = ""
For Each gruposSeguridad In objetoUsuario.Groups
If gruposSeguridadUsuario = "" Then
gruposSeguridadUsuario = gruposSeguridad.Name
Else
gruposSeguridadUsuario = gruposSeguridadUsuario + ", " + gruposSeguridad.Name
End If
Next
'Mostramos los datos del usuario
MsgBox("Nombre completo: " & objetoUsuario.Get("Fullname") & vbCrLf & _
"Descripción: " & objetoUsuario.Get("Description") & vbCrLf & _
"Nombre: " & objetoUsuario.Get("Name") & vbCrLf & _
"Carpeta de inicio: " & objetoUsuario.Get("HomeDirectory") & vbCrLf & _
"Script de inicio: " & objetoUsuario.Get("LoginScript") & vbCrLf & _
"Último inicio de sesión: " & ultimoInicioSesion & vbCrLf & _
"Perfil: " & objetoUsuario.Get("Profile") & vbCrLf & _
"Estado de la cuenta: " & estadoCuenta & vbCrLf & _
"Grupos seguridad: " & gruposSeguridadUsuario, vbInformation + vbOKOnly)
objetoUsuario = Nothing
Else
MsgBox("No existe el usuario " + nombreUsuario + " o el dominio " + dominio, vbExclamation + vbOKOnly)
End If
'cSalir:
' Exit Sub
'
'cError:
' MsgBox "Error " + CStr(Err.Number) + " " + Err.Description
' GoTo cSalir
End Sub

On Click command and not adding text when text box is blank

On Click I want my button to not add text when me.txtAddNote is blank and display a message prompting the user to enter text or cancel. And when me.txtAddNote has text I would like the On Click to enter the text. Currently, my code adds text on both conditions and even before the msgbox pops up. Any help is appreciated, thank you.
Private Sub cmdAddNote_Click()
Dim LName As String
On Error Resume Next
LName = DLookup("[LNAME]", "[qryEmpDepDes]", "[EMP_NO]='" & Me.txtUserID & "'")
[NOTES] = Date & ": " & Me.txtAddNote & " (" & Me.txtUserID & " " & LName & ")" & vbNewLine & vbNewLine & [NOTES]
Me.txtAddNote = ""
Me.cmdAddNote.Enabled = True
Me.cmdClose.Enabled = True
Me.cmdClose.SetFocus
'5-16-2016 testing blank text box'
If Me.txtAddNote = "" Then
If MsgBox("No text is entered. Hit OK to enter text. Hit CANCEL to close out.", vbOKCancel) = vbOK Then
End If
Else
DoCmd.Close
End If
End Sub
Try checking the content of txtAddNote prior to anything else?
Private Sub cmdAddNote_Click()
Dim LName As String
If Me.txtAddNote.Text = "" Then
response = MsgBox("No text is entered. Hit OK to enter text. Hit CANCEL to close out.", vbOKCancel)
If response = vbOK Then
' do whatever you needed
Else
Exit Sub ' Exit the sub if Cancel was clicked
End If
End If
On Error Resume Next
LName = DLookup("[LNAME]", "[qryEmpDepDes]", "[EMP_NO]='" & Me.txtUserID & "'")
[NOTES] = Date & ": " & Me.txtAddNote & " (" & Me.txtUserID & " " & LName & ")" & vbNewLine & vbNewLine & [NOTES]
Me.txtAddNote = ""
Me.cmdAddNote.Enabled = True
Me.cmdClose.Enabled = True
Me.cmdClose.SetFocus
DoCmd.Close
End Sub