I currently have a variable called databaseinformation in a script that I am writing. I want to seperate this into two variables called Instance_Name and Database_Name
The string in question:
[MSSQLSERVER]BESMgmt.BAK
In this instance the Instance_Name is MSSQLSERVER and the Database_Name is BESMgmt. The string will not necessarily end in .BAK but stripping the last four characters off the variable would be fine. The Instance_Name and Database_Name will change values and length.
Thanks for any help in advance
#Trinitrotoluene: Working sample code --
Option Explicit
Dim ToBeSplit, Instance_Name, Database_Name
Dim SplitMe
Dim Position
ToBeSplit = "[MSSQLSERVER]BESMgmt.BAK"
SplitMe = Split(ToBeSplit, "]")
If IsArray(SplitMe) Then
Instance_Name = SplitMe(0)
Database_Name = SplitMe(1)
End If
Instance_Name = Replace(Instance_Name, "[", "")
If InStr(Database_Name, ".") > 0 Then
Database_Name = Left(Database_Name, Len(Database_Name) - 4)
End If
Response.Write "Instance_Name = " & Instance_Name & "<br>"
Response.Write "Database_Name = " & Database_Name
Or do it with a regular expression object, this makes you more flexible, allthough some will say that you have two problems now:
Option Explicit
Dim regEx, matches
Dim myString : myString = "[MSSQLSERVER]BESMgmt.BAK"
set regEx = new RegExp
regEx.pattern = "\[(.*)\](.*).{4}"
set matches = regEx.Execute(myString)
msgbox "Instance_name: " & matches(0).subMatches(0) & vbNewLine & "Database_name: " & matches(0).subMatches(1)
Related
I have a situation where I need to strip out HTML code from some text. However, some of the input text includes lists, and I want to retain the numbering in that case.
If I do
result = Regex.Replace(result, "<li>", vbNewLine & "1. ", RegexOptions.IgnoreCase)
Then after stripping out the other HTML tags, I end up with:
1. List item one
1. List item two
1. List item three
Is there a way to get the index of the match during replacement?
so for example:
result = Regex.Replace(result, "<li>", vbNewLine & replacementIndex + 1 & " ", RegexOptions.IgnoreCase)
Then after stripping out the other HTML tags, I would get:
1. List item one
2. List item two
3. List item three
Is this possible??
Note: This is inside a function, so that each list is handled separately, and unordered lists get bullets (*) instead.
This should be a good starting point. #"(\<ul\>)((.|\n)*?)(\<\/ul\>)" this will match everything in between the tags.
It's messy, but something like the following. Only change one at a time. This may be slow for large data sets.
int lineNbr = 1;
string newResult = result.Replace("(?i)<li>", vbNewLine & (lineNbr++).ToString() & '. ', 1);
while (newResult != result)
{
result = newResult;
newResult = result.Replace("(?i)<li>", vbNewLine & (lineNbr++).ToString() & '. ', 1);
}
Here's how I ended up doing it - first, find each ordered list:
Dim result As String = rawText
Dim orderedLists As MatchCollection = Regex.Matches(rawText, "<ol>.*?</ol>", RegexOptions.Singleline)
For Each ol As Match In orderedLists
result = Replace(result, ol.Value, EncodeOrderedList(ol.Value))
Next
And the function to convert each one:
Private Function EncodeOrderedList(ByVal rawText As String) As String
Dim result As String = rawText
result = Regex.Replace(result, "<ol>\s*<li>", "1. ", RegexOptions.IgnoreCase)
result = Regex.Replace(result, "</li>\s*</ol>", vbNewLine & vbNewLine, RegexOptions.IgnoreCase)
Dim bullets As MatchCollection = Regex.Matches(rawText, "</li>\s*<li>")
Dim i As Integer = 2
For Each li As Match In bullets
result = Replace(result, li.Value, vbNewLine & i & ". ", 1, 1)
i += 1
Next
Return result
End Function
I haven't tested it on nested lists.
I need to copy a range from an Excel file into Outlook, then send it as an email. It needs to be embedded into the email itself. I found this code which works great, with one exception: It is centering the range in the middle of the "page" in outlook, and I need it to align to the left.
I am assuming this is done in HTML but I do not know that language. Here is the code I am using:
Option Explicit
Public Sub prcSendMail()
Dim objOutlook As Object, objMail As Object
Set objOutlook = CreateObject(Class:="Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With objMail
.To = "Mike.Marshall#worldpay.us"
.Subject = "Hallo"
.HTMLBody = fncRangeToHtml("Summary", "B2:G26")
.Display 'zum testen
' .Send
End With
Set objMail = Nothing
Set objOutlook = Nothing
End Sub
Private Function fncRangeToHtml( _
strWorksheetName As String, _
strRangeAddress As String) As String
Dim objFilesytem As Object, objTextstream As Object, objShape As Shape
Dim strFilename As String, strTempText As String
Dim blnRangeContainsShapes As Boolean
strFilename = Environ$("temp") & "\" & _
Format(Now, "dd-mm-yy_h-mm-ss") & ".htm"
ThisWorkbook.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=strFilename, _
Sheet:=strWorksheetName, _
Source:=strRangeAddress, _
HtmlType:=xlHtmlStatic).Publish True
Set objFilesytem = CreateObject("Scripting.FileSystemObject")
Set objTextstream = objFilesytem.GetFile(strFilename).OpenAsTextStream(1, -2)
strTempText = objTextstream.ReadAll
objTextstream.Close
For Each objShape In Worksheets(strWorksheetName).Shapes
If Not Intersect(objShape.TopLeftCell, Worksheets( _
strWorksheetName).Range(strRangeAddress)) Is Nothing Then
blnRangeContainsShapes = True
Exit For
End If
Next
If blnRangeContainsShapes Then _
strTempText = fncConvertPictureToMail(strTempText, Worksheets(strWorksheetName))
fncRangeToHtml = strTempText
Set objTextstream = Nothing
Set objFilesytem = Nothing
Kill strFilename
End Function
Public Function fncConvertPictureToMail(strTempText As String, objWorksheet As Worksheet) As String
Const HTM_START = "<link rel=File-List href="
Const HTM_END = "/filelist.xml"
Dim strTemp As String
Dim lngPathLeft As Long
lngPathLeft = InStr(1, strTempText, HTM_START)
strTemp = Mid$(strTempText, lngPathLeft, InStr(lngPathLeft, strTempText, ">") - lngPathLeft)
strTemp = Replace(strTemp, HTM_START & Chr$(34), "")
strTemp = Replace(strTemp, HTM_END & Chr$(34), "")
strTemp = strTemp & "/"
strTempText = Replace(strTempText, strTemp, Environ$("temp") & "\" & strTemp)
fncConvertPictureToMail = strTempText
End Function
Is there some code to left align the range I am copying into Outlook?
I have W7 x64, Excel 2013 and Outlook 2013.
Thanks!
add this after your objTextstream.Close
strTempText = Replace(strTempText, "align=center x:publishsource=", "align=left x:publishsource=")
This worked for me
With objMail
.To = "Bofa#deeznutz.com"
.cc = ""
.Subject = "BR1 Summary for Adjustments +/- >$250"
.HTMLBody = "<table width='100'><tr><td align=left>" + fncRangeToHtml("weekly adjustments report", Sheet1.UsedRange.Address) + "</td></tr></table>" & "<br>" & "<b>" & "<font size=4>" & "Adjustments +/- >$250" & "</font>" & "</b>" & fncRangeToHtml("Sheet1", Sheet2.UsedRange.Address)
VBA likes the quotes and the spaces. but in that last line of code you can either quote all of you HTML functions or break it up. but once you are finished using that like bold, you have to "/function" to end it before it likes the information. the & and + work the same.
I have a text file having three fields category name, image name and link or URL. The three fields are stored in the text file separated by comma. I want to read the textfile values and display them one by one that is in a column format. So all the category names will be displayed in one column, image name in one column and link in one column.
I have read the text file and i get all the contents in text file in a variable. The content that i get in variable is as follows:
glass,glassbowlcategory.jpg,www.google.com glass,glassbowlcategory.jpg,www.google.com glass bowl,images1.jpg,http://www.fitnessfirstusa.com/catalog.asp?Brand=LG%20Sciences
In the above string first one is category name, second is image name and third is link.
I have used the folllowing code to read text file.
Sub BuildFileList(strFolder)
Dim strFileName1
Dim strSearchText
Dim objFSO, objTextFile
Dim strReadLineText
Dim intLineNumber,strNewContents
Dim strLineNumbers
Dim objFile
' Name of text file to search:
'
'strFileName = "readme.txt"
strFileName1 = "saveimagename.txt"
Const ForReading = 1
Const ForWriting = 2
'' Create an instance of the the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(Server.MapPath(strFileName1))
intLineNumber = 0
'
strLineNumbers = ""
Do While Not objTextFile.AtEndOfStream
intLineNumber = intLineNumber + 1
strReadLineText = objTextFile.ReadLine
' response.Write(strReadLineText)
strNewContents = strNewContents & strReadLineText & vbCrLf
response.Write(strNewContents)
'
Loop
end sub
Please advise how can i split the contents that i get in the variable and display them
For tabular data
Const ForReading = 1
Const ForWriting = 2
Dim objTextFile
Dim intLineNumber, strNewContents, strReadLineText
dim data, columns
strFileName1 = "saveimagename.txt"
Set objTextFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(Server.MapPath(strFileName1))
intLineNumber = 0
strLineNumbers = ""
data = split(objTextFile.readall(), vbcrlf)
for intLineNumber = 0 to ubound(data)
columns = split(data(intLineNumber), ",", 3)
if (ubound(columns) = 2) then
strNewContents = strNewContents & "<tr><td>" & columns(0) & "</td><td>" & columns(1) & "</td><td>" & columns(2) & "</td></tr>" & vbcrlf
end if
next
response.write "<table>" & strNewContents & "</table>"
perhaps you could use Microsoft ActiveX Database Objects (ADO) for that?
here are some links:
Much ADO about Text Files
Microsoft ODBC Desktop Database Drivers
and some sample code:
'http://msdn.microsoft.com/en-us/library/ms974559.aspx
dim conn : set conn = server.createObject("ADODB.Connection")
dim rs : set rs = server.createObject("adodb.recordset")
dim sql
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
importPath & ";" &_
"Extended Properties=""text;HDR=" & HDR & ";FMT=Delimited"""
sql = "SELECT * FROM " & myImportFile
rs.open sql, conn, adOpenStatic, adLockOptimistic, adCmdText
Here's my code
Dim RefsUpdate As String() = Session("Refs").Split("-"C)
Dim PaymentsPassedUpdate As String() = Session("PaymentsPassed").Split("-"C)
Dim x as Integer
For x = 1 to RefsUpdate.Length - 1
Dim LogData2 As sterm.markdata = New sterm.markdata()
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''"+ RefsUpdate(x) +"'' AND bookno = ''"+ Session("number") +"'' ') SET alpaid = '"+PaymentsPassedUpdate(x) +"', paidfl = 'Y', amountdue = '0' ")
Dim drSetUpdatePaymentFlags As DataSet = Data.Blah(queryUpdatePaymentFlags)
Next
I don't get any errors for this but it doesn't seem to working as it should
I'm passing a bookingref like this AA123456 - BB123456 - CC123456 - etc and payment like this 50000 - 10000 - 30000 -
I basically need to update the db with the ref AA123456 so the alpaid field has 50000 in it.
Can't seem to get it to work
Any ideas?
Thanks
Jamie
I'm not sure what isn't working, but I can tell you that you are not going to process the last entry in your arrays. You are going from 1 to Length - 1, which is one short of the last index. Therefore, unless your input strings end with "-", you will miss the last one.
Your indexing problem mentioned by Mark is only one item, but it will cause an issue. I'd say looking at the base your problem stems from not having trimmed the strings. Your data base probably doesn't have spaces leading or trailing your data so you'll need to do something like:
Dim refsUpdateString as string = RefsUpdate(x).Trim()
Dim paymentsPassedUpdateString as string = PaymentsPassedUpdate(x).Trim()
...
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''" & refsUpdateString & "'' AND bookno = ''" & Session("number") & "'' ') SET alpaid = '" & paymentsPassedUpdateString & "', paidfl = 'Y', amountdue = '0' ")
Also, I would recommend keeping with the VB way of concatenation and use the & character to do it.
I have project in development where string operations like "Hi " + variable + ", welcome to Project" are used at many places (given example is very minor one).
One of the requirement is to convert it to string.format style.
It is very long and tedious job, where I would not like to break earlier working code due to any human error might happen while converting it.
I would like to if any Macro or VS command which I can create to handle it. Just like we mark block of code and do Extract function in Re-factor options.
I felt the code was a little long to post here, but I posted an answer at my blog:
http://www.brianschmitt.com/2010/08/converting-concatenated-string-into.html
-- EDIT --
Per comment here is the relevant Macro - not sure why you cannot access...
Public Sub ConvertToStringFormat()
DTE.UndoContext.Open("ConvertToStringFormat")
Dim textSelection As TextSelection = DTE.ActiveDocument.Selection
Dim output As String = "string.Format(""{0}"", {1})"
Dim delimt As String = ", "
Dim fmtdTostring As String = ".tostring("""
Dim txtSelection As String() = System.Text.RegularExpressions.Regex.Split(textSelection.Text.Trim, "\+\s_[+\n\r\t]|&\s_[+\n\r\t]|\+|&")
Dim hardStrings As String = String.Empty
Dim valueStrings As String = String.Empty
Dim counter As Int16 = 0
For Each str As String In txtSelection
Dim tmpString As String = str.Trim
If tmpString.StartsWith("""") Then
hardStrings &= tmpString.Substring(1, tmpString.Length - 2)
Else
Dim fmt As String = String.Empty
Dim indxToString As Int32 = 0
If tmpString.ToLower.Contains(fmtdTostring) Then
indxToString = tmpString.ToLower.IndexOf(fmtdTostring)
fmt = tmpString.Substring(indxToString + 11, tmpString.Length - tmpString.ToLower.IndexOf(""")", indxToString) - 1)
End If
If fmt <> String.Empty Then
hardStrings &= "{" & counter.ToString & ":" & fmt & "}"
valueStrings &= tmpString.Substring(0, indxToString) & delimt
Else
hardStrings &= "{" & counter.ToString & "}"
valueStrings &= tmpString & delimt
End If
counter += 1
End If
Next
If valueStrings <> String.Empty Then valueStrings = valueStrings.Substring(0, valueStrings.Length - delimt.Length)
textSelection.Text = String.Format(output, hardStrings, valueStrings)
DTE.UndoContext.Close()
End Sub