Excel VSTO - Hide multiple columns lambda function issue - VB.NET - vb.net

I've been trying to figure out what is wrong with my code below, but no success so far.
My simple task is to hide multiple Excel columns using VSTO / VB.NET.
This works:
Dim app As Excel.Application = Globals.ThisAddIn.Application
Dim act_sheet As Excel.Worksheet = app.ActiveSheet
act_sheet.Range("A:A").EntireColumn.Hidden = True
act_sheet.Range("B:B").EntireColumn.Hidden = True
This doesn't work:
Dim app As Excel.Application = Globals.ThisAddIn.Application
Dim act_sheet As Excel.Worksheet = app.ActiveSheet
Dim base_hide As New List(Of String)({"A:A", "B:B"})
base_hide.ForEach(Function(x) act_sheet.Range(x).EntireColumn.Hidden = True)
I get no errors compiling it, the string address is taken correctly. Any idea?
Thank you,
C

Found what caused the issue. Running a ForEach loop as lambda with Function() would expect to return something. My code inside the function never run. Changing it to Sub() works as expected.
base_hide.ForEach(Sub(x) act_sheet.Range(x).EntireColumn.Hidden = True)

Related

OpenXML: Losing Custom Document Property After Editing Word Document

Using DocumentFormat.OpenXML, I am trying to add a custom property to a Word document and then later read the property. The following code "appears" to do just that:
Dim os As OpenSettings = New OpenSettings() With {
.AutoSave = False
}
Dim propVal As String = "Test Value"
Using doc As WordprocessingDocument = WordprocessingDocument.Open(filename, True, os)
Dim cPart As CustomFilePropertiesPart = doc.CustomFilePropertiesPart
If cPart Is Nothing Then
cPart = doc.AddCustomFilePropertiesPart
cPart.Properties = New DocumentFormat.OpenXml.CustomProperties.Properties()
End If
Dim cPart As CustomFilePropertiesPart = doc.CustomFilePropertiesPart
Dim cProps As Properties = cPart.Properties
For Each prop As CustomDocumentProperty In cProps
If prop.Name = "TranscriptID" Then
prop.Remove()
Exit For
End If
Next
Dim newProp As CustomDocumentProperty = New CustomDocumentProperty() With {
.Name = "TranscriptID"
}
newProp.VTBString = New VTBString(propVal)
newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"
cProps.AppendChild(newProp)
Dim pid As Integer = 2
For Each item As CustomDocumentProperty In cProps
item.PropertyId = pid
pid += 1
Next
cProps.Save()
End Using
This code is modeled after code found here:
https://learn.microsoft.com/en-us/office/open-xml/how-to-set-a-custom-property-in-a-word-processing-document
It appears to work in this scenario:
Execute code from above.
Execute code from above again.
At #2 I expect to find the CustomFilePropertiesPart and the property value and my expectation is met.
The problem appears in this scenario:
Execute code from above.
Open document using Microsoft Word, save and close.
Execute code from above again.
What happens in this scenario is that the CustomFilePropertiesPart is missing, whereas it should be found. It is as if Microsoft Word does not successfully read this object, so when the document is save, the object is lost. This suggests to me that there is something that there is something wrong with my code. If you can see what it is, or if you have a comparable working example that I could compare it with, I would appreciate hearing from you. I feel like I correctly followed the Microsoft example, but obviously I did not and I am having trouble seeing where I departed. Thanks.
OK, I found this wonderful tool called the Office Productivity Tool. It has a code generation feature, so I was able to compare what I was doing with what Word does. Basically the problem was with setting the property value. This snippet does the trick:
Dim cProps As Properties = cPart.Properties
Dim val As DocumentFormat.OpenXml.VariantTypes.VTLPWSTR = New DocumentFormat.OpenXml.VariantTypes.VTLPWSTR
val.Text = tr.ID.ToString
Dim newProp As CustomDocumentProperty = New CustomDocumentProperty() With {
.Name = "TranscriptID",
.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"
}
newProp.Append(val)
cProps.AppendChild(newProp)

Calling a variable in VBA Formula

I am very new in VBA and have the following problem:
I have a code like this
IE.Document.getElementsByName("selectedNotifiers")(tparty).Checked = True
The purpose is to check a checkbox on a website. The code works. Now I want to use tparty as a variable based on a excel cell.
I tired this
Dim tparty As String
tparty = ThisWorkbook.Sheets("Sheet1").Value(Range("q" & rn))
IE.Document.getElementsByName("selectedNotifiers")(tparty).Checked = True
but is causing the IE crashing. Any help plz.
Latest status. even Tried this
Dim tparty As String
tparty = "SFD0087G"
IE.Document.getElementsByName("selectedNotifiers")(tparty).Checked = True
no luck.

VBA Groupwise Email

I'm using Excel 2013, Windows 7, Groupwise 12.
The code should be pretty straight forward, but I keep getting an error
"Active X component can't create object"
I've made sure the references are there according to the Groupwise's development documents which is simply their "gwcma1.dll" and I just can't figure out what is going on.
Theory right now is that Groupwise was installed some way that didn't populate the registry information needed for the code to create the object even though it is in the object browser.
Code:
Dim gwAccount As GroupwareTypeLibrary.Account2
Set gwApp = CreateObject("NovellGroupwareSession")
I've used this code for years on older versions of excel and windows and groupwise, and I can't figure out what has changed.
---EDIT---
Here's the beginning part of the code. After this is just standard loops and logic that all works.
Here's the first part of it. After this point, it's just standard loops and and logic.
Sub EmailPDFs()
Dim i, k As Long
Dim PhysicianCount As Long
Dim StartPoint As Long
Dim CurrentNPI As Long
Dim CurrentEmail As String
Dim CurrentFileName As String
Dim CurrentFilePath As String
Dim CurrentDate As String
Dim EmailBody As String
'Declaration for Email
Dim gwMessage As GroupwareTypeLibrary.Message2
Dim gwAccount As GroupwareTypeLibrary.Account2
Dim gwApp As GroupwareTypeLibrary.Application
Set gwApp = CreateObject("NovellGroupwareSession")
Set gwAccount = gwApp.Login()
---EDIT 2---
I tried Application2 and still the same error. I think I was trying the older one and the properties were the same on the object, but Application2 let you do proxy email access which I wasn't worried about.
For creating a new application, I may need a refresh on the syntax but I'm assuming you're suggesting something like:
Dim xlApp as Excel.Application
Set xlApp = New Excel.Application 'Early Binding
Set xlApp = CreateObject(“Excel.Application”) 'Late Binding

unable to run Exchange Powershell through vb.net application

So I'm going round in circles trying to get this to work, I've been trying for two days and I just can't figure it out.
I have the following vb function that takes a created powershell script, and should run it in powershell. Everything works fine, until the point at which the command pipeline is invoked. At this point, no commands run.
As you can see, I have tried to add the Microsoft.Exchange.Management.PowerShell.E2010 snapin to the runspace, it didn't like that at all stating something along the lines of the snapin didnt exist (which it does), and also when I run the code as shown, no commands are recognised as valid. I even added the specific command "Add-PSSnapin" to try and load any Exchange snapins, but it states that "Add-PSSnapin" is not recognised as a valid command.
If I pause the program just before the commands are involked, I can see every command within the pipeline, in the correct format. If I copy and paste the command text in the pipeline directly into a powershell window, it runs fine.
My code is below, any suggestions welcome.
edit: I have also tried adding the line "Add-PSSnapin Ex" (with an asterisk each side of Ex - I cant figure the formatting out on this, sorry)
to try and load the Exchange PS Snapins as the first thing the script would run (opposed to setting this up in the runspace) but no luck
Private Function scriptRunner(ByVal scripttorun As String) As String
Dim initial As InitialSessionState = InitialSessionState.CreateDefault()
Dim result As String = ""
Dim lineFromScript As String = ""
Dim reader As New StreamReader(tempScript)
Dim rsConfig As RunspaceConfiguration = RunspaceConfiguration.Create()
Dim snapInException As New PSSnapInException
Dim strUserName As String = "DOMAIN\USER"
Dim strPassword As String = "PASSWORD"
Dim SecuredPSWD As New System.Security.SecureString()
For Each character As Char In strPassword
SecuredPSWD.AppendChar(character)
Next
Dim wsmConnectionInfo As WSManConnectionInfo
Dim strSystemURI As String = "http://SERVER.DOMAIN/powershell?serializationLevel=Full"
Dim strShellURI As String = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"
Dim powerShellCredentials As PSCredential = New PSCredential(strUserName, SecuredPSWD)
wsmConnectionInfo = New WSManConnectionInfo(New Uri(strSystemURI), strShellURI, powerShellCredentials)
Dim runspace As Runspace = RunspaceFactory.CreateRunspace(wsmConnectionInfo)
Runspace.Open()
' runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", snapInException)
Dim pipeLine As Pipeline = runspace.CreatePipeline()
Dim command As Command = New Command("")
' TEST >> pipeLine.Commands.Add("Add-PSSnapin *Ex*")
Do While reader.Peek() <> -1
lineFromScript = Nothing
lineFromScript = reader.ReadLine()
pipeLine.Commands.Add(lineFromScript)
'command.Parameters.Add(lineFromScript)
'pipeLine.Commands.Add(command)
Loop
'' Run the contents of the pipeline
Dim psObjCollection As Collection(Of PSObject) = pipeLine.Invoke()
runspace.Close()
runspace.Dispose()
Return ""
End Function
I ended up working around the problem rather than fixing it.
I moved the script code into the vb.net application, and wrote each line to a file, i.e.
writer.WriteLine("Add-PSSnapin *Ex*")
Then I loaded the script through PowerShell as an application;
Dim exeStartInfo As System.Diagnostics.ProcessStartInfo
Dim exeStart As New System.Diagnostics.Process
exeStartInfo = New System.Diagnostics.ProcessStartInfo("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")
exeStartInfo.Arguments = ("-command work\scriptbuilder.ps1")
exeStartInfo.WorkingDirectory = "C:\ExchangeManager\"
exeStartInfo.UseShellExecute = False
exeStart.StartInfo = exeStartInfo
exeStart.Start()
exeStart.Close()
Not ideal but it got the job done.

FeatureCursor instance passed to Search method of ISelectionSet throws NullReferenceException

I am trying to create a custom tool in VB.Net for arcmap. But im having a problem with FeatureCursor passed to ISelectionSet's Search() method.
Here's a portion of my code:
Dim pSelSet As ISelectionSet = provFSel.SelectionSet
Dim provCursor As IFeatureCursor
pSelSet.Search(spatialFilter, True, provCursor)
Dim provFeature As IFeature = provCursor.NextFeature
A blue squiggle appears under provCursor inside Search() that says "Variable 'provCursor' is passed by reference before it has been assigned a value. A null reference exception could result at runtime."
Ive tried
Dim provCursor As IFeatureCursor = New FeatureCursor
but a squiggle under New FeatureCursor says "'ESRI.ArcGIS.Geodatabase.FeatureCursorClass.Friend Sub New()' is not accessible in this context because it is 'Friend'.".
I also tried
Dim provCursor As IFeatureCursor = Nothing
but with no success.
In all my debugging attempts, Arcmap crashed with this error: A first chance exception of type 'System.NullReferenceException' occurred in Microsoft.VisualBasic.dll
Can somebody help me figure out whats wrong with my code? Ill really appreciate any help.
-spearman
Im not actually sure if error occurs in the above codes or in the prior codes. Im therefore posting the whole subprocedure content:
Dim pPoint As IPoint = pMxDoc.CurrentLocation
Dim provFSel As IFeatureSelection = provinceLayer
Dim pGeom As IGeometry = pPoint.Shape
Dim spatialFilter As ISpatialFilter = New SpatialFilter
With spatialFilter
.Geometry = pGeom
.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin
End With
Dim pSelSet As ISelectionSet = provFSel.SelectionSet
Dim provCursor As IFeatureCursor
pSelSet.Search(spatialFilter, True, provCursor)
Dim provFeature As IFeature = provCursor.NextFeature
Try:
pSelSet.Search(spatialFilter, True, out provCursor)