Exporting to Excel using ClosedXML.Excel and making a header row - vb.net

Below is a snippet of a function I am using to successfully export a GridView to Excel and this code merges a range of cells, and formats the text. Now I would also like to make this header row appear on every print page should a user elect to print the worksheet. I'm thinking that this must be a configurable item, so what would be the syntax for this please?
Dim xlDoc As New XLWorkbook()
xlDoc.AddWorksheet("Export")
Dim xlWS As IXLWorksheet = xlDoc.Worksheets(0)
xlWS.Row(1).Cell(1).Value = "some text"
xlWS.Row(1).Cell(1).Style.Fill.BackgroundColor = XLColor.FromArgb(255, 255, 102)
xlWS.Row(1).Cell(1).Style.Font.Bold = True
xlWS.Range("A1", "G1").Merge()
xlWS.Range("A1", "G1").Style.Border.OutsideBorder = XLBorderStyleValues.Thin
xlWS.Range("A2", "G2").SetAutoFilter()

Related

How to set text and background color in Spreadsheetgear?

In SpreadsheetGear 2012 I want to set:
text color to white.
background color of the cell to black.
I've tried variations of:
Sheet_Obj.Cells(0,0).Style.NumberFormat = "#"
Sheet_Obj.Cells(0,0).Interior.Color = Spreadsheetgear.Color.FromArgb(&H0)
Sheet_Obj.Cells(0,0).Style.Font.Color = SpreadsheetGear.Color.FromArgb(&HFFFFFF)
Sheet_Obj.Cells(0,0).Value = "Terabytes"
But have not been able to get anything to work.
Example:
Your code is mixing up applying formatting directly to the cell itself versus the cell Style that the cell uses. Please see my answer here for more details on this.
If you only want to affect a particular cell with a particular format, you would need to use IRange.Interior / IRange.Font.Color / etc. Example:
Dim workbook As SpreadsheetGear.IWorkbook = SpreadsheetGear.Factory.GetWorkbook()
Dim Sheet_Obj As SpreadsheetGear.IWorksheet = workbook.ActiveWorksheet
' This modifies the format of the cell directly.
Sheet_Obj.Cells(0, 0).Interior.Color = SpreadsheetGear.Colors.Black
Sheet_Obj.Cells(0, 0).Font.Color = SpreadsheetGear.Colors.White
Sheet_Obj.Cells(0, 0).NumberFormat = "#"
If you want all cells in a workbook to have a particular format, then modifying the Style for which those cells use (which is by default the "Normal" style) would be a good way to go about it. You can access the current IStyle used by a particular cell via IRange.Style. You can access the entire collection of available IStyles via the IWorkbook.Styles collection. Example:
' This modifies whatever IStyle is currently used by this cell (probably the "Normal"
' style). All other cells which also use this still will be affected as well.
Sheet_Obj.Cells(0, 0).Style.Interior.Color = SpreadsheetGear.Colors.Black
Sheet_Obj.Cells(0, 0).Style.Font.Color = SpreadsheetGear.Colors.White
Sheet_Obj.Cells(0, 0).Style.NumberFormat = "#"
' Assuming you are modifying the "Normal" style, this code is equivalent to the above code.
Dim style As SpreadsheetGear.IStyle = workbook.Styles("Normal")
style.Interior.Color = SpreadsheetGear.Colors.Black
style.Font.Color = SpreadsheetGear.Colors.White
style.NumberFormat = "#"

Multi criteria filter in VBA (Not equal to)

I am using the below code in Blue prism for filtering in excel for multi criteria.
But i am not able to filter multi criteria for Not equal to scenario.
Dim wb As Object
Dim excel as Object
Dim range as Object
Try
wb = GetWorkbook(Handle, Workbook)
excel = wb.Application
range = excel.Range(FRange)
Dim listOfValues as Array
listOfValues = Split(FCriteria,";")
wb.worksheets(Worksheet).select
range.select
range.Autofilter(FCol,listOfValues,7)
Success = True
Catch e As Exception
Success = False
Message = e.Message
Finally
wb = Nothing
End Try
Please help me tweaking the script
I'm almost sure that there is no filter option to set a "negative list". You can specify either a (positive) list of values (this is what your code does so far, for this you have to set the 7 as third parameter), or you can give a maximum of 2 individual criteria (in Excel, choose "Custom Filter" to set them.
You should play with the filter directly in Excel and try to set it like you want. Once you are satisfied with it, clear the filter, record a macro and repeat the filtering. Go to the VBA editor and see what's in there. It is straightforward to translate this into C# code.
But:
It's not possible to set any filtering by code (neither C# nor VBA) that you cannot set via the Excel GUI
I would question what you are trying to do. Since you are using Blue Prism, you should be trying to access the underlying data in a BP Collection(VB DataTable), rather than applying a filter, which is a visual tool for humans to further play with the interface. The robot will still have to do something with the filtered data, and it far easier to write code to proceed with data during the loop.
Otherwise use the Filter Collection Page of the 'Utilities - Collection Manipulation' VBO to get a filtered collection.
Also you are using VBA Split function, when you should use Split in VB as a method of the String.
Try this for a new page in the 'Utilities - Collection Manipulation' VBO(untested):
Dim NewRow As DataRow
Collection_Out = Collection_In.Clone
Dim Select_Concat As String
Select_Concat = "NOT(" & fieldName & " = '" & [String].Join("' OR " & fieldName & " = '", FCriteria.Split(";"c)) & "')"
For Each parentRow As DataRow In Collection_In.Select(Select_Concat)
NewRow = Collection_Out.NewRow
For Each c As DataColumn In NewRow.Table.Columns
NewRow(c.ColumnName) = parentRow(c.ColumnName)
Next c
Collection_Out.Rows.Add(NewRow)
Next parentRow
NewRow = Nothing
Collection_In = Nothing
Inputs: Collection_In(Collection), fieldName(Text), FCriteria(Text)
Outputs: Collection_Out(Collection)
You first need to get the entire range into an unfiltered Collection(which will be your Collection_In to this page, and then get the filtered Collection out....

VBA replace logo in Excel file

I have a little strange question. I used to have few reports worked upon daily.
All these are in Excel and had a logo of the company in all the sheets of each file.
However, now the company name is changed and hence a new logo needs to be replaced in place of the existing. Wanted to check if this replacement can be done with VBA.
I tried with the application.shapes method. But, was confused to proceed further.
Try this....
Sub ChangePicture(strNewPath As String)
Dim oOld As Picture
Dim oNew As Picture
Set oOld = ActiveSheet.Pictures(1)
Set oNew = ActiveSheet.Pictures.Insert(strNewPath)
oNew.Left = oOld.Left
oNew.Top = oOld.Top
oNew.Width = oOld.Width
oNew.Height = oOld.Height
oOld.Delete
End Sub

Single line thread/sequenced execution of formulas in Excel

I wrote a simple macro function in VBA for Excel to extract text appearing in a particular location in an HTML document, first retrieving the HTML document from a URL value in another cell. The macro function itself is not important, except for the fact that it sends an HTTP request and creates an HTML file object, which I fear will cause Excel to crash if I paste, say, a column of 100 or more URLs and it starts trying to calculate all the values at once. I can see that it stops and churns for a moment if I drag the formula down 10 cells where there is already a column of URLs. Is there a setting to force Excel to calculate one formula at a time, so that it may take longer but is less likely to freeze up or crash?
Update: I incorporated a static collection variable into the function to at least avoid repeated slowdowns retrieving the same HTML in the same worksheet:
Function GetUSPatentAbstract(ByVal url As String) As String
Static colAbstract As New Collection
Dim abstract As String
On Error Resume Next
abstract = colAbstract(url)
`If there is no abstract for the URL in the collection yet, then it is retrieved:
If Err.Number <> 0 Then
Dim description As String
Dim abstractStart As Long
Dim abstractEnd As Long
Dim abstractLength As Long
Set html_doc = CreateObject("htmlfile")
Set xml_obj = CreateObject("MSXML2.XMLHTTP")
xml_obj.Open "GET", url, False
xml_obj.send
html_doc.body.innerhtml = xml_obj.responseText
Set xml_obj = Nothing
description = html_doc.body.innertext
abstractStart = InStr(description, "Abstract") + 8
abstractEnd = InStr(description, "Inventors:")
abstractLength = abstractEnd - abstractStart
abstract = Mid(description, abstractStart, abstractLength)
colAbstract.Add Item:=abstract, Key:=url
End If
On Error GoTo 0
GetUSPatentAbstract = abstract
End Function

Remove sas content from Excel with VBA (MS Office Add-in)

I've figured out how to use the MS Office Add-in to run a SAS Stored Process from within Excel (using an input stream) to obtain outputs.
Everytime I run this, new columns are inserted to accommodate the new output. Also, additional content is added to the workbook.
My understanding of the SAS Add-in object model is poor, so I was hoping someone could help me:
1) Remove the existing content with VBA before running the process again; or
2) Write VBA code to refresh existing content only (within the same output range).
The code I'm using is:
Sub sasTests()
Application.ScreenUpdating = False
Dim sas As SASExcelAddIn
Set sas = Application.COMAddIns.Item("SAS.ExcelAddIn").Object
Dim inputStream As SASRanges
Set inputStream = New SASRanges
inputStream.Add "Prompts", Worksheets("sasInput").Range("sasInput")
sas.InsertStoredProcess "/Shared Data/C139/sasTests", _
Worksheets("sasOutput").Range("A1"), , , inputStream
End Sub
Many thanks!
PS. If anyone has any handy references for the SAS Add-in for MS Office, please provide links
You could clear the range containing the existing content with the .Clear method. If this range were in columns M:P, you could use the following line:
sheetNameHere.Range("M:P").Clear
If you added that line after setting
Application.ScreenUpdating = False
I believe this would imitate a "refresh" of the data.
This will remove all old components from the workbook. I am not sure how to refresh all but assuming its similar:
Sub DeleteSasContent()Dim sas As SASExcelAddIn
Set sas = Application.COMAddIns.Item("sas.exceladdin").Object
Dim stpList As SASStoredProcesses
Dim dataList As SASDataViews
Dim pivotList As SASPivotTables
Dim reportList As SASReports
Set stpList = sas.GetStoredProcesses(ThisWorkbook)
Set dataList = sas.GetDataViews(ThisWorkbook)
Set pivotList = sas.GetPivotTables(ThisWorkbook)
Set reportList = sas.GetReports(ThisWorkbook)
For i = 1 To stpList.Count
stpList.Item(i).Delete
Next i
For i = 1 To dataList.Count
dataList.Item(i).Delete
Next i
For i = 1 To pivotList.Count
pivotList.Item(i).Delete
Next i
For i = 1 To reportList.Count
reportList.Item(i).Delete
Next i
End Sub
See the SAS help here http://support.sas.com/kb/45/606.html