strikethrough a paragraph in a doc using interop in c# - c#-3.0

I have searched a word in a paragraph and if that word is found in any of the paragraph then i need to strikethrough the paragraph.Till now i have tried
Public Function StrikethroughPara(ByVal searchstring As String) As Boolean
Dim Content As String
For b As Integer = 1 To objword.ActiveDocument.Paragraphs.Count - 1
Content = objword.ActiveDocument.Paragraphs(b).Range.Text
Try
If Regex.IsMatch(Content, searchstring) Then
**objword.Selection.Font.StrikeThrough = 9999998**//This is not working
'objword.Selection.Paragraphs.Style.StrikeThrough = WdConstants.wdToggle
End If
Catch ex As Exception
End Try
Next
End Function
Please Provide me the solution if possible.

Related

macro executed when document is loaded

After losing files from a HD, data rescue gave me back most of them, but with abstract names (such as file000123.xlsx). I need to rename them using cell values (client name, invoice ref).
I could make a Basic macro that works for this, if I open the files and start the macro myself for each one of those files.
As I have thousands of files to rename, I need that macro to execute on its own, either when documents are loaded, otherwise on a selected folder.
I assigned my macro to the "document loaded" event via the "tools-Customize-Events" menu. Then, I get a "wrong property value" error on the 1st line, the one defining the function.
Is my way of doing wrong ? Do I have to modify the macro for it to work there ?
Context :
This macro is in "My macros", not within the documents.
using libreOffice 7 on Linux
working on .xlsx files
Thanks for any help, my libreOffice Basic is even poorer than my English.. B-)
My code :
function getFullRep(sPath As String) As String
Dim cpt As Integer
Dim buf As String
Const SLASH = "/"
buf = ""
for cpt = Len(sPath) to 1 step -1
if Mid(sPath, cpt, 1) = SLASH then
buf = Left(sPath, cpt)
exit for
end if
next
getFullRep = buf
end function
Sub Main
Dim oDoc as Object
Dim sG2 as String
Dim sO2 as String
Dim sO as String
Dim sPathBackupFolder as String
Dim filespec As string
Dim laDate As String
Dim myfilename As String
Dim oFeuille As Object
Dim sNomFeuille As String
oDoc = ThisComponent
sPathBackupFolder = getFullRep (oDoc.location)
oFeuille = oDoc.getCurrentController().getActiveSheet()
sNomFeuille = oFeuille.getName()
laDate = Format(Now(),"YYMMDDhhmmss")
If oFeuille.GetCellRangeByName("G14").String <>"" Then
sG2 = oFeuille.GetCellRangeByName("G14").String
sO2 = oFeuille.GetCellRangeByName("A15").String
else
sG2 = oFeuille.GetCellRangeByName("G15").String
sO2 = oFeuille.GetCellRangeByName("A16").String
End If
sO = Replace(sO2, "Facture N°", "")
'Chemin et nom de fichier composé
myfilename = sPathBackupFolder+sG2+" - "+sO+" - "+laDate+".ods"
'Enregistrer sous
dim document as object
dim dispatcher as object
' ----------------------------------------------------------------------
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
' ----------------------------------------------------------------------
dim args1(1) as new com.sun.star.beans.PropertyValue
args1(0).Name = "URL"
args1(0).Value = ConvertToUrl(myfilename) 'On converti le chemin
args1(1).Name = "FilterName"
args1(1).Value = "calc8"
dispatcher.executeDispatch(document, ".uno:SaveAs", "", 0, args1())
oDoc.store
oDoc.close(True)
End Sub
You are getting the error because the document has not completely opened yet. Instead, attach to the event "View Created", and make sure to save to "LibreOffice" (as opposed to individual document).
By the way, it would be a good idea to give your sub a more appropriate name than "Main".
Hope that helps!

How to cut a string from the end in UIPATH

I have this string: "C:\Procesos\rrhh\CorteDocumentos\Cortados\10001662-1_20060301_29_1_20190301.pdf" and im trying to get this part : "20190301". The problem is the lenght is not always the same. It would be:
"9001662-1_20060301_4_1_20190301".
I've tried this: item.ToString.Substring(66,8), but it doesn't work sometimes.
What can I do?.
This is a code example of what I said in my comment.
Sub Main()
Dim strFileName As String = ""
Dim di As New DirectoryInfo("C:\Users\Maniac\Desktop\test")
Dim aryFi As FileInfo() = di.GetFiles("*.pdf")
Dim fi As FileInfo
For Each fi In aryFi
Dim arrname() As String
arrname = Split(Path.GetFileNameWithoutExtension(fi.Name), "_")
strFileName = arrname(arrname.Count - 1)
Console.WriteLine(strFileName)
Next
End Sub
You could achieve this using a simple regular expressions, which has the added benefit of including pattern validation.
If you need to get exactly eight numbers from the end of file name (and after an underscore), you can use this pattern:
_(\d{8})\.pdf
And then this VB.NET line:
Regex.Match(fileName, "_(\d{8})\.pdf").Groups(1).Value
It's important to mention that Regex is by default case sensitive, so to prevent from being in a situations where "pdf" is matched and "PDF" is not, the patter can be adjusted like this:
(?i)_(\d{8})\.pdf
You can than use it directly in any expression window:
PS: You should also ensure that System.Text.RegularExpressions reference is in the Imports:
You can achieve it by this way as well :)
Path.GetFileNameWithoutExtension(Str1).Split("_"c).Last
Path.GetFileNameWithoutExtension
Returns the file name of the specified path string without the extension.
so with your String it will return to you - 10001662-1_20060301_29_1_20190301
then Split above String i.e. 10001662-1_20060301_29_1_20190301 based on _ and will return an array of string.
Last
It will return you the last element of an array returned by Split..
Regards..!!
AKsh

How to retrieve the value of an Input field and use it to modify a placeholder in a LibreOffice Basic macro?

I've spent two days on this and I'm still not able to figure it out 8-)
I have a LibreOffice Writer document with some Placeholders (Insert -> Fields -> More Fields -> Functions -> Placeholder -> Image) and Input fields (Insert -> Fields -> More Fieds -> Functions -> Input field) and I need to retrieve the value of an Input field and use it to replace a specified Placeholder in the same document.
To be more precise. I have an Input field where I enter for example 123
and somewhere in the document is a button, which triggers a macro, and this macro should:
retrieve the current value of the specified (named?) Input field ("123"),
"replace" a specified (named?) Placeholder with an image loaded from http://domain.tld/image/123.png
Is this somehow possible? Would be great, because I'm trying to to insert externally generated barcodes into my document...
These are both "Text fields", and some information and macro examples are in Andrew Pitonyak's book OpenOffice Macros Explained (available as a free pdf download from http://www.pitonyak.org/oo.php). The wiki page also has some good background.
Form controls (from the toolbar "Form controls") are named, so they have an advantage when working with macros. Text fields, however - the kind you have in your document - are not named, so you have to cycle through all the fields in a document, or highlight a particular run of text and cycle through the field within the highlighted area to find the one you are after. The Pitonyak document has examples of both methods.
Assuming the document has only one input field, this StarBasic code will print its current value:
Sub DisplayFields
Dim oEnum As Object
Dim oField As Object
oEnum = ThisComponent.getTextFields().createEnumeration()
Do While oEnum.hasMoreElements()
oField = oEnum.nextElement()
If oField.getPresentation(True) = "Input field" Then
Print "Input field contents: " & oField.getPresentation(False)
Exit Do
End If
Loop
End Sub
As far as I can tell, there is no API to replace a placeholder with its designated content. There might be a way with the dispatcher - the list of dispatch commands tantalizingly includes "FieldDialog" - but I wasn't able to find any documentation or examples.
I think what you'd have to do is find the field, put your cursor there, insert the image, then delete the placeholder field. Some more StarBasic code (again, assuming there's only a single placeholder field in the document):
Sub InsertImage
Dim oEnum As Object
Dim oField As Object
Dim oAnchor As Object
Dim oText As Object
Dim oCursor As Object
Dim FileName As String
Dim FileURL As String
Dim objTextGraphicObject As Object
oEnum = ThisComponent.getTextFields().createEnumeration()
Do While oEnum.hasMoreElements()
oField = oEnum.nextElement()
If oField.getPresentation(True) = "Placeholder" Then
oAnchor = oField.Anchor
oText = oAnchor.getText()
oCursor = oText.createTextCursorByRange(oAnchor.getEnd)
FileName = "C:\after zoo.JPG"
FileURL = convertToURL(FileName)
objTextGraphicObject = ThisComponent.createInstance("com.sun.star.text.TextGraphicObject")
REM Optional to set the size
' Dim objSize as New com.sun.star.awt.Size
' objSize.Width = 3530
' objSize.Height = 1550
' objTextGraphicObject.setSize(objSize)
objTextGraphicObject.GraphicURL = FileURL
oText.insertTextContent(oCursor.Start, objTextGraphicObject, false)
oField.dispose()
Exit Do
End If
Loop
End Sub

Access VBA Classes Arrays

Im trying to use some classes that will hold invoice data and I cant seem to get it working. I just want it to save details of an invoice in an array. Heres the code, maybe someone can figure it out.
Also id like for the LineItems to take a random number of product items, not sure how to do that yet. Im doing this to eventually send the data through a web service from ms access.
Here is the other code for struct_XOrder:
Public OrderNumber As String
Public ClientShortName As String
'"LineItems" is an array with elements defined as struct_LineItem
'See Complex Types: Arrays in Microsoft Office 2003 Web Services Toolkit Help
'for details on implementing arrays.
Public LineItems As Variant
Public OrderError As String
Heres the struct_LineItem:
Public ProductSKU As String
Public Qty As Long
Public UnitPrice As Variant
Public ItemComment As String
Public ItemError As String
Heres my main code
Sub webservicetest()
Dim NewOrder As struct_XOrder
Dim LineItems(1 To 2) As Variant
Dim Xline(1 To 2) As Variant
Set Xline() = struct_LineItem
Set NewOrder = New struct_XOrder
Set NewOrder.LineItems() = New struct_LineItem
Set NewOrder.LineItems() = New Xline
'Xline = New struct_LineItem
Xline(1).ItemComment = "items"
Xline(1).Qty = 10
NewOrder.LineItems() = Xline()
NewOrder.ClientShortName = "DemoClient"
NewOrder.OrderNumber = "12345"
'Xline(1).ItemComment = "item1"
'Xline(1).Qty = 5
Debug.Print NewOrder.ClientShortName
Debug.Print NewOrder.OrderNumber
'For i = LBound(Xline) To UBound(Xline): Debug.Print Xline(i): Next
'Debug.Print Xline(1).ItemComment
'Debug.Print Xline(1).Qty
End Sub
See comments for explanations.
Use Type instead within VBA to create structs. Also, you do not need to use Set the way you are.
Additionally, use Option Explicit to require variable declarations whenever using VBA unless you want a nightmare.
This all can go in the same module.
'use this
Option Explicit
'VBA structs are defined like the following
'and do not need "new" (similar to other languages)
'when creating them
Type struct_LineItem
ProductSKU As String
Qty As Long
UnitPrice As Variant
ItemComment As String
ItemError As String
End Type
Type struct_XOrder
OrderNumber As String
ClientShortName As String
'make this more clear
LineItems() As struct_LineItem
OrderError As String
End Type
Sub webservicetest()
Dim NewOrder As struct_XOrder
Dim LineItems(1 To 2) As Variant
Dim Xline(1 To 2) As struct_LineItem
'you can't do this, you need to specify which element
'in XLine you want to set
'Set Xline() = struct_LineItem
Dim myStruct As struct_LineItem
Xline(1) = myStruct
'you don't need "set"
NewOrder.LineItems = Xline()
'this won't update as if it's a reference, btw
Xline(1).ItemComment = "items"
Xline(1).Qty = 10
NewOrder.LineItems = Xline()
NewOrder.ClientShortName = "DemoClient"
NewOrder.OrderNumber = "12345"
Debug.Print NewOrder.ClientShortName
Debug.Print NewOrder.OrderNumber
'don't do ":" as this makes code unbearably not readable...
'For i = LBound(Xline) To UBound(Xline): Debug.Print Xline(i): Next
Dim i As Integer
For i = 1 To UBound(NewOrder.LineItems)
Debug.Print NewOrder.LineItems(i).ItemComment
Next i
End Sub

OpenXML editing docx

I have a dynamically generated docx file.
Need write the text strictly to end of page.
With Microsoft.Interop i insert Paragraphs before text:
int kk = objDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref wMissing);
while (objDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref wMissing) != kk + 1)
{
objWord.Selection.TypeParagraph();
}
objWord.Selection.TypeBackspace();
But i can't use same code with Open XML, because pages.count calculated only by word.
Using interop impossible, because it so slowwwww.
There are 2 options of doing this in Open XML.
create Content Place holder from Microsoft Office Developer Tab at the end of your document and now you can access this Content Place Holder programatically and can place any text in it.
you can append text driectly to your word document where it will be inserted at the end of your text. In this approach you got to write all the stuff to your document first and once you are done than you can append your document the following way
//
public void WriteTextToWordDocument()
{
using(WordprocessingDocument doc = WordprocessingDocument.Open(documentPath, true))
{
MainDocumentPart mainPart = doc.MainDocumentPart;
Body body = mainPart.Document.Body;
Paragraph paragraph = new Paragraph();
Run run = new Run();
Text myText = new Text("Append this text at the end of the word document");
run.Append(myText);
paragraph.Append(run);
body.Append(paragraph);
// dont forget to save and close your document as in the following two lines
mainPart.Document.Save();
doc.Close();
}
}
I haven't tested the above code but hope it will give you an idea of dealing with word document in OpenXML.
Regards,