Format string bold at a bookmark location - vba

I am a newbie and am making a userform that inputs data into a letter. There is a string that I need to bold and underline.
With .Bookmarks("bidDate").Range.InsertBefore
.Text = inputBidM & " " & inputBidD & ", " & inputBidY
.Font.Bold = True
.Font.Underline = True
End With
I found this http://computer-programming-forum.com/1-vba/8e9aacaf425425ad.htm to get what I have above but am getting a Compile Error: Invalid or Unqualified reference.
Any help is much appreciated.
Edit: Here is the code for that section. I have everything else commented out.
Private Sub startButton_Click()
' Inserting Addendum Info from fill in boxes
With ActiveDocument
.Bookmarks("addenDate").Range.InsertBefore inputAddenM & " " & inputAddenD & ", " & inputAddenY
.Bookmarks("addenDateA").Range.InsertBefore inputAddenM & " " & inputAddenD & ", " & inputAddenY
.Bookmarks("contractNo").Range.InsertBefore inputContractNo
.Bookmarks("contractNoA").Range.InsertBefore inputContractNo
.Bookmarks("fapNo").Range.InsertBefore inputFAPNo
.Bookmarks("descrip").Range.InsertBefore inputDescrip
.Bookmarks("addenNo").Range.InsertBefore inputAddenNo
.Bookmarks("addenNoA").Range.InsertBefore inputAddenNo
.Bookmarks("addenNoB").Range.InsertBefore inputAddenNo
.Bookmarks("bidDate").Range.Text inputBidM & " " & inputBidD & ", " & inputBidY
.Font.Bold = True
.Font.Underline = True
End With
End Sub

The With keyword lets you perform multiple actions on an object without needing to type the object out for each line. The code you show could be written without the With and End With by putting ActiveDocument in front of each .Bookmarks line. You can see how this saves time typing and it can be easier to read :-)
Since you want to do more with the last bookmark than just insert text, you can add (nest) another With...End With to let you work with that Range, something like this:
Private Sub startButton_Click()
' Inserting Addendum Info from fill in boxes
With ActiveDocument
.Bookmarks("addenDate").Range.InsertBefore inputAddenM & " " & inputAddenD & ", " & inputAddenY
.Bookmarks("addenDateA").Range.InsertBefore inputAddenM & " " & inputAddenD & ", " & inputAddenY
.Bookmarks("contractNo").Range.InsertBefore inputContractNo
.Bookmarks("contractNoA").Range.InsertBefore inputContractNo
.Bookmarks("fapNo").Range.InsertBefore inputFAPNo
.Bookmarks("descrip").Range.InsertBefore inputDescrip
.Bookmarks("addenNo").Range.InsertBefore inputAddenNo
.Bookmarks("addenNoA").Range.InsertBefore inputAddenNo
.Bookmarks("addenNoB").Range.InsertBefore inputAddenNo
With .Bookmarks("bidDate").Range
.Text = inputBidM & " " & inputBidD & ", " & inputBidY
.Font.Bold = True
.Font.Underline = True
End With
End With
End Sub

The following does work:
Sub test()
With Selection
.GoTo What:=wdGoToBookmark, Name:="bidDate"
.Text = "blah blah blah"
.Font.Bold = True
.Font.Underline = True
End With
End Sub
A colon before .Bookmarks is only possible when another With statement was used. That is why you are getting the error message.

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

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

How to create a comment box with time and date stamp in Access using VBA

Completely new to VBA and need help with detailed instructions (dummy version for me).
I have a table with various columns and the following columns, specifically:
ReviewerComments
NewComment
I created a form with both of these fields and need to create an Append Comment button that moves the text from NewComment field and appends it to ReviewerComment field and time/date stamps the comments as they are added. I named this button cmdAppendComment.
I had seen someone else post something and I tried, but as I am completely new to this I know I messed it up. Any help is greatly appreciated.
This is what the VBA code looks like right now:
Private Sub cmdAppendComment_Click()
If (IsNull(NewComment.Value)) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
If (IsNull(ReviewerComments.Value)) Then
ReviewerComments.Value = NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
Else
ReviewerComments.Value = ReviewerComments.Value & _
vbNewLine & vbNewLine & _
NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
End If
NewComment.Value = ""
End Sub
I have some suggestions for your code:
1. Do not check if a textbox is null but how many characters your textbox has. You should always do it that way because otherwise you tend to get errors.
If (len(Me.NewComment.Value & "") > 0) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
Here you check the length of the string in your textbox. You need to append "" because otherwise you tend to get null-errors or something similar.
2. You forgot to reference the objects in your form correctly. You have your form and in that form you put your textboxes and also your VBA-code. Your can reference all your objects with "Me.[FormObjects]".
The compiler complains that "NewComment.Value" or "ReviewerComment.Value" is not initialized or in other words not dimensioned. With correct reference this should stop.
Private Sub cmdAppendComment_Click()
If (len(Me.NewComment.Value & "") > 0) Then
MsgBox ("Please provide a comment before clicking" & _
"on the Append Comment button.")
Exit Sub
End If
If (IsNull(Me.ReviewerComments.Value)) Then
Me.ReviewerComments.Value = Me.NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
Else
Me.ReviewerComments.Value = Me.ReviewerComments.Value & _
vbNewLine & vbNewLine & _
Me.NewComment.Value & " ~ " & _
VBA.DateTime.Date & " ~ " & VBA.DateTime.Time
End If
Me.NewComment.Value = ""
End Sub

VB.NET - using textfile as source for menus and textboxes

this is probably a bit tense and I'm not sure if this is possible at all.
But basically, I'm trying to create a small application which contains alot of PowerShell-code which I want to run in an easy matter.
I've managed to create everything myself and it does work. But all of the PowerShell code is manually hardcoded and this gives me a huge disadvantage.
What I was thinking was creating some sort of dynamic structure where I can read a couple of text files (possible a numerous amount of text files) and use these as the source for both the comboboxes and the richtextbox which provovides as the string used to run in PowerShell.
I was thinking something like this:
Combobox - "Choose cmdlet" - Use "menucode.txt" as source
Richtextbox - Use "code.txt" as source
But, the thing is, Powershell snippets need a few arguments in order for them to work.
So I've got a couple of comboboxes and a few textboxes which provides as input for these arguments. And this is done manually as it is right now. So rewriting this small application should also search the textfile for some keywords and have the comboboxes and textboxes to replace those keywords. And I'm not sure how to do this.
So, would this requre a whole lot of textfiles? Or could I use one textfile and separate each PowerShell cmdlet snippets with something? Like some sort of a header?
Right now, I've got this code at the eventhandler (ComboBox_SelectedIndexChanged)
If ComboBoxFunksjon.Text = "Set attribute" Then
TxtBoxUsername.Visible = True
End If
If chkBoxTextfile.Checked = True Then
If txtboxBrowse.Text = "" Then
MsgBox("You haven't choses a textfile as input for usernames")
End If
LabelAttribute.Visible = True
LabelUsername.Visible = False
ComboBoxAttribute.Visible = True
TxtBoxUsername.Visible = False
txtBoxCode.Text = "$users = Get-Content " & txtboxBrowse.Text & vbCrLf & "foreach ($a in $users)" & vbCrLf & "{" & vbCrLf & "Set-QADUser -Identity $a -ObjectAttributes #{" & ComboBoxAttribute.SelectedItem & "='" & TxtBoxValue.Text & "'}" & vbCrLf & "}"
If ComboBoxAttribute.SelectedItem = "Outlook WebAccess" Then
TxtBoxValue.Visible = False
CheckBoxValue.Visible = True
CheckBoxValue.Text = "OWA Enabled?"
txtBoxCode.Text = "$users = Get-Content " & txtboxBrowse.Text & vbCrLf & "foreach ($a in $users)" & vbCrLf & "{" & vbCrLf & "Set-CASMailbox -Identity $a -OWAEnabled" & " " & "$" & CheckBoxValue.Checked & " '}" & vbCrLf & "}"
End If
If ComboBoxAttribute.SelectedItem = "MobileSync" Then
TxtBoxValue.Visible = False
CheckBoxValue.Visible = True
CheckBoxValue.Text = "MobileSync Enabled?"
Dim value
If CheckBoxValue.Checked = True Then
value = "0"
Else
value = "7"
End If
txtBoxCode.Text = "$users = Get-Content " & txtboxBrowse.Text & vbCrLf & "foreach ($a in $users)" & vbCrLf & "{" & vbCrLf & "Set-QADUser -Identity $a -ObjectAttributes #{msExchOmaAdminWirelessEnable='" & value & " '}" & vbCrLf & "}"
End If
Else
LabelAttribute.Visible = True
LabelUsername.Visible = True
ComboBoxAttribute.Visible = True
txtBoxCode.Text = "Set-QADUser -Identity " & TxtBoxUsername.Text & " -ObjectAttributes #{" & ComboBoxAttribute.SelectedItem & "='" & TxtBoxValue.Text & " '}"
If ComboBoxAttribute.SelectedItem = "Outlook WebAccess" Then
TxtBoxValue.Visible = False
CheckBoxValue.Visible = True
CheckBoxValue.Text = "OWA Enabled?"
txtBoxCode.Text = "Set-CASMailbox " & TxtBoxUsername.Text & " -OWAEnabled " & "$" & CheckBoxValue.Checked
End If
If ComboBoxAttribute.SelectedItem = "MobileSync" Then
TxtBoxValue.Visible = False
CheckBoxValue.Visible = True
CheckBoxValue.Text = "MobileSync Enabled?"
Dim value
If CheckBoxValue.Checked = True Then
value = "0"
Else
value = "7"
End If
txtBoxCode.Text = "Set-QADUser " & TxtBoxUsername.Text & " -ObjectAttributes #{msExchOmaAdminWirelessEnable='" & value & "'}"
End If
End If
Now, this snippet above lets me either use a text file as a source for each username used in the powershell snippet. Just so you know :) And I know, this is probably coded as stupidly as it gets. But it does work! :)
It'll probably get fairly horrible to debug when you've been away from it for a year and are trying to figure out how it hangs together, but if you're doing it I'd suggest that this might be a good time to use XML, since you can then create a nice structure to the files easily that will be fairly easy to understand.
<commands>
<command>
<name>Cmd1</name>
<buttonText>NiceName</buttonText>
<parameters>
<parameter>textBox1</parameter>
<parameter>textBox2</parameter>
<parameter>comboBox1</parameter>
</parameters>
<code>your code here</code>
</command>
<command>
...
</command>
</commands>
You'd have to be careful if your script code contains any characters that can interfere with the xml though.