Adding a hyperlink in word, with vb.net - vb.net

I'm currently trying to add a hyperlink to a web url in word through a VB program. I'm stumbling around to try and find the proper syntax and what I need to accomplish this, because I've been getting a lot of unhelpful VBA examples, which is not what I need at all.
My code looks like this:
sPara2 = oDoc.Content.Paragraphs.Add
sPara2.Range.Text = attachmentRdr("attachmentName")
sPara2.Range.Hyperlinks.Add(attachmentRdr("attachmentPath"))
sPara2.Format.SpaceAfter = 24 '24 pt spacing after paragraph.
sPara2.Range.InsertParagraphAfter()
where attachmentRdr is a sqlDatareader reading strings of text (attachment name, and path) from a database. If I run this, I get an error for bad parameters (which gets' proced off of the hyperlinks.add()).

Pass range through as the first parameter to the Add function, followed by your URL:
Dim range As Microsoft.Office.Interop.Word.Range
range = Me.Application.Selection.Range
range.Hyperlinks.Add(range, "http://www.microsoft.com")

Related

How to Convert from Date Object into a Range to Display at Bookmark in Word VBA?

Context: I am trying to create a document to where the document prompts the user for information. Right now, I just trying to understand the reason I cannot get the date turned into a range to be able to display at the bookmark.
I have tried creating different types of objects to associate with Date but I just do not understand the reason I am getting a compile error.
Sub TodayDate()
Dim dateVariable
dateVariable = Date
Set dateVariable = ActiveDocument.Bookmarks("bmkTodayDate").Range
dateVariable.Text = dateVariable.value
I am wanting to display the date at the posted bookmark location ("bmkTodayDate"), but I keep getting error messages. What is the correct object or the correct code that I should have used?
So I did some searching on the net, and I came up with a solution. Cindy Meister was right that I need to declare some objects into existence. I didn't realized that the bookmark object "bmkDate" needed to come into existence as well.
Sub TodayDate()
Dim bmkDate As Bookmark
Set bmkDate = ActiveDocument.Bookmarks("Date")
bmkDate.Range.Text = Date
Things to note: First, thank you Miles Flatt for your input. What I found that works for me is that "Date" is an actual posted/inserted bookmark within the Word document; the today variable Date is in the default format, so it will display mm/dd/yyyy at the location; and finally, the modifier/suffixes .Range.Text is what really helped. The Range.Text returns or sets the text in the specified range or selection.

How to restrict swear word input when using a textbox within Visual Basic

I have had several ideas yet most of the solutions online only restrict certain keys or only numbers, not full strings.
I want a solution that as soon as a keypress of a swear word has been inputted, VB detects it then disallows it. I have been able to do exact string matching so if a user puts the work F*** in, then it shows an error message, but this would not work if the user decided to put in "F***nugget". It would not be elegant nor time feasible to enter every possible combination of swear words. Thanks in advance for help.
If e.KeyChar = "F***" Then
SelectionTextBoxTeamName.Clear()
MessageBox.Show("Please choose something else")
You need a 'string contains' function.
If you're writing in vb.net try String's Contains function, which is used like this:
Dim b As Boolean
b = s1.Contains(s2)
If you're not writing in .net
try InStr function. You can use it as follows:
InStr("find the comma, in the string", ",")
EDIT: after op's comment
If you want to check several swears you can put them in an array and check for each:
Dim swears = {"F***", "S***"}
Dim hasSwears As Boolean = false
For Each swear As String In swears
If InStr(textBox.Text, swear) > 0 Then
hasSwears = true
End If
Next
Now you know if there are any swears according to hasSwears.

Visual Basic (2010) - Using variables in embedded text files?

Ive always been able to just search for what I need on here, and I've usually found it fairly easily, but this seems to be an exception.
I'm writing a program in Visual Basic 2010 Express, it's a fairly simple text based adventure game.
I have a story, with multiple possible paths based on what button/option you choose.
The text of each story path is saved in its own embedded resource .txt file. I could just write the contents of the text files straight into VB, and that would solve my problem, but that's not the way I want to do this, because that would end up looking really messy.
My problem is that I need to use variable names within my story, here's an example of the contents of one of the embedded text files,
"When "+playername+" woke up, "+genderheshe+" didn't recognise "+genderhisher+" surroundings."
I have used the following code to read the file into my text box
Private Sub frmAdventure_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim thestorytext As String
Dim imageStream As Stream
Dim textStreamReader As StreamReader
Dim assembly As [Assembly]
assembly = [assembly].GetExecutingAssembly()
imageStream = assembly.GetManifestResourceStream("Catastrophe.CatastropheStoryStart.png")
textStreamReader = New StreamReader(assembly.GetManifestResourceStream("Catastrophe.CatastropheStoryStart.txt"))
thestorytext = textStreamReader.ReadLine()
txtAdventure.Text = thestorytext
End Sub
Which works to an extent, but displays it exactly as it is in the text file, keeps the quotes and the +s and the variable names instead of removing the quotes and the +s and replacing the variable names with what's stored within the variables.
Can anyone tell me what I need to change or add to make this work?
Thanks, and apologies if this has been answered somewhere and I just didn't recognise it as the solution or didn't know what to search to find it or something.
Since your application is compiled, you cannot just put some of your VB code in the text file and have it executed when it is read.
What you can do, and what is usually done, is that you leave certain tags inside your text file, then locate them and replace them with the actual values.
For example:
When %playername% woke up, %genderheshe% didn`t recognise %genderhisher% surroundings.
Then in your code, you would find all the tags:
Dim matches = Regex.Matches(thestorytext, "%(\w+?)%")
For Each match in matches
' the tag name is now in: match.Groups(1).Value
' replace the tag with the value and replace it back into the original string
Next
Of course the big problem still remains - which is how to fill in the actual values. Unfortunately, there is no clean way to do this, especially using any local variables.
You can either manually maintain a Dictionary of tag names and their values, or use Reflection to get the values directly at the runtime. While it should be used carefully (speed, security, ...), it will work just fine for your case.
Assuming you have all your variables defined as properties in the same class (Me) as the code that reads and processes this text, the code will look like this:
Dim matches = Regex.Matches(thestorytext, "%(\w+?)%")
For Each match in matches
Dim tag = match.Groups(1).Value
Dim value = Me.GetType().GetField(tag).GetValue(Me)
thestorytext = thestorytext.Replace(match.Value, value) ' Lazy code
Next
txtAdventure.Text = thestorytext
If you don't use properties, but only fields, change the line to this:
Dim value = Me.GetType().GetField(tag).GetValue(Me)
Note that this example is rough and the code will happily crash if the tags are misspelled or not existing (you should do some error checking), but it should get you started.

Parse String to Array or DataTable

I'm trying to parse a long boring text document and parse and format it.
"7/29/2012 1:25:20 PM","Summary Plan/Second Floor /Master_VAV_2-24","Source :OEnd"
"7/29/2012 11:25:23 AM","Summary Plan/Second Floor /Master_VAV_2-24","Source :OStart"
I'd like to parse each value between the quotes but I cant find anything online to help me, I believe it's a matter of knowing what to call it and search for.
"date", "location", "type" would be the 3 values I want to parse it into, then I could run a loop for each item in datatable and format it as required.
ANY HELP would be great, thank you!
I'm thinking of using RegEx to get the rows and add them manually to an array, something like this.
Dim rx As New Regex(",", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
Dim matches As MatchCollection = rx.Matches(strSource)
For Each match As Match In matches
Dim matchValue As String = match.Value
If Not list.Contains(matchValue) Then
list.Add(matchValue)
End If
Next
This format appears to be CSV - use one of the many free and open source CSV parsers (google ".NET CSV parser" will return many results.
There is one that comes built in, in the Microsoft.VisualBasic.FileIO namespece - the TextFieldParser.

VS 2010 macro - select from here to there

I'm writing a macro to let me replace the spaces in a string in my code file with underscores. I've gotten as far as finding the beginning and end of the string as instances of VirtualPoint. Now I'm trying to select from the first VirtualPoint to the second. And I can't figure it out.
I know the VirtualPoints are correct, because I'm using MessageBox.Show to tell me their values when I run the macro. I just don't know the correct command to set the TextSelection from the first to the second. I've tried this:
selection.MoveToPoint(firstVirtualPoint)
selection.MoveToPoint(secondVirtualPoint, True)
This seems like it ought to work, but it doesn't. The cursor just moves to the end of the line (as far as I can tell).
Does anybody know the correct command for doing this?
As these things tend to go, after I give up, suddenly it hits me. Perhaps this will help someone else, though.
A fuller sample of the code is this:
Dim selection As TextSelection =
CType(DTE.ActiveDocument.Selection, TextSelection)
selection.StartOfLine()
selection.FindText("some string at start")
Dim pointAfterStart = selection.BottomPoint
selection.FindText("some string at end")
Dim pointBeforeEnd = selection.TopPoint
selection.MoveToPoint(pointAfterIt)
selection.MoveToPoint(pointBeforeLambda, True)
The idea is to find the initial text, then the ending text, and then select everything in between. What I found in the debugger was that the values in pointAfterStart and pointBeforeEnd were changing. Perhaps deceived by the name (since System.Drawing.Point is a struct), I wasn't realizing they were references that pointed to the current selection position.
I solved it this way:
selection.FindText("It ")
Dim pointAfterIt = selection.BottomPoint.CreateEditPoint
selection.FindText(" = () =>")
Dim pointBeforeLambda = selection.TopPoint.CreateEditPoint
This made copies of the selection points, so that they didn't change when the selection moved later.