I have a variable, emailBody, which is set to a string stored in a database. The email body is set to a string via a dlookup function.
emailBody = DLookup("emailBody", "listAdditions", "Id = " & itemType)
The string that email body is set to includes an IIf function (which includes a dlookup function). When
?emailBody is entered in the immediate window during runtime, it shows that emailBody is set to the following string:
The new commodity is" & Iif(dlookup("IsVague", "CommodityType", "Description= " & newItem)="1", "vague.", "not vague.")
However, I want the dlookup and IIf functions to be evaluated and their results stored in the string. How do I properly format the emailBody string ("the new commodity...") in my database so that the functions will be evaluated and the results stored in the emailBody variable?
Your question is a bit unclear, but if [Id] (Or [Description]) is a string, then you Dlookup must be like this:
emailBody = DLookup("emailBody", "listAdditions", "Id = '" & itemType & "'")
or
emailBody = DLookup("emailBody", "listAdditions", "Id = """ & itemType & """")
That is, your constant should be surrounded by quotes. You can either use ' (single quote) or "" (doubled double quote).
I am somewhat concerned about the value of newitem, but in general you can use Eval:
s = """The new commodity is"" & " _
& "Iif(dlookup(""IsVague"", ""CommodityType"", ""Description= "" & newItem)=""1"", ""vague."", ""not vague."")"
s2 = Eval(s)
I am not sure that this is the way to go, think about it.
So you have this exact string stored in a table field, and you want Access/VBA to evaluate it, correct?
"The new commodity is " & Iif(dlookup("IsVague", "CommodityType", "Description= " & newItem)="1", "vague.", "not vague.")
If so, try the Eval() command:
emailBody = Eval(DLookup("emailBody", "listAdditions", "Id = " & itemType))
Related
I'm looking for a way to validate those dialog boxes that pop up while updating a word document via excel vba.
The type of fields that I use is MailMerge Fields type "Fillin"
WordObj.ActiveDocument.MailMerge.Fields.AddFillIn
I'd like to write in them if possible too.
Update operation
Dialog box
It is by no means clear what you're trying to achieve. When you use:
ActiveDocument.MailMerge.Fields.AddFillIn
the resulting field doesn't show up in the document until something is done to cause it to update (e.g. performing the mailmerge). If you want the field to show up, use something like:
Dim wdFld As Object
With WordObj.ActiveDocument
Set wdFld = .Fields.Add(.Range.Characters.Last, -1, "QUOTE ""Default Text""", False)
wdFld.Code.Text = "FILLIN ""Some prompt"" \d ""Default Text"" \o"
End With
Other than that, you really do need to both explain how and why you're using a FILLIN field and post the code that updates it when the mailmerge is executed. After all, the use of a FILLIN field typically means the user is supposed to both make an input and press the OK/Cancel button.
To allow the specification of different ranges, prompts and defaults, you might use something like:
Sub FILLIN(StrBkMk As String, StrPrmpt As String, StrDflt As String)
Dim wdFld As Object
Dim quote As String
quote = char(34)
With WordObj.ActiveDocument
Set wdFld = .Fields.Add(.Bookmarks(StrBkMk).Range, -1, "QUOTE " & quote & StrDflt & quote, False)
wdFld.Code.Text = "FILLIN " & StrPrmpt & " \d " & StrDflt & " \o \* MERGEFORMAT "
End With
End Sub
where 'StrBkMk' is the name of a bookmark you want to position the field at. You'd then call the above code with something like:
Call FILLIN("FILLIN1", nom_signet, nouveau_texte_signet)
Or, if you're passing multi-word strings:
Call FILLIN("FILLIN1", "" & nom_signet & "", "" & nouveau_texte_signet & "")
I am connecting to a SQL Server and am trying to limit the results by adding parameters. The first parameter I added, #sdate, worked just fine. But, now I am trying to add a second parameter which is not working. I want the field, LP_EOC_DATA.PL, to only be returned if the length of the string is greater than 6 characters long. The code below executed, and like I say, the dates returned were correct, but it also returned values from LP_EOC_DATA.PL that had string lengths less than 6. Please let me know if you know how to get this to work. Thanks in advance.
Sub doSQL()
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim myReader As SqlDataReader
Dim sqlString As String = "SELECT LP_EOC_DATA.PL as PLs, LP_EOC_DATA.cDate as ReadDate, LP_EOC_LOV.LOCATION as Location " &
"FROM LP_EOC_DATA INNER JOIN LP_EOC_LOV ON LP_EOC_DATA.PIC = LP_EOC_LOV.PIC " &
"WHERE LP_EOC_DATA.cDate > (#sdate) AND LEN(LP_EOC_DATA.PL) > #slen1 " &
"UNION SELECT dbo.VT_DATA.PL as PLs, dbo.VT_DATA.cDate as ReadDate, dbo.VT_LOV.LOCATION as Location " &
"FROM dbo.VT_DATA INNER JOIN dbo.VT_LOV ON dbo.VT_DATA.PIC = dbo.VT_LOV.PIC " &
"WHERE dbo.VT_DATA.cDate > (#sdate) AND LEN(dbo.VT_DATA.PL) > #slen1 " &
"ORDER BY ReadDate;"
myConn = New SqlConnection("SERVER=ServerName;UID=uName;" &
"PWD=Password;")
myCmd = myConn.CreateCommand
myCmd.CommandText = sqlString
myCmd.Parameters.AddWithValue("#sdate", DateTimePicker1.Value)
myCmd.Parameters.AddWithValue("#slen1", 6)
'myCmd.Parameters.AddWithValue("#rx1", "'%[^0-9a-z]%'")
'myCmd.Parameters.AddWithValue("#rx2", " dbo.VT_DATA.PL NOT LIKE '%[^0-9a-z]%'")
myConn.Open()
myReader = myCmd.ExecuteReader()
Table.Load(myReader)
DataGridView1.Visible = True
DataGridView1.DataSource = Table
lblTotal.Text = Table.Rows.Count
End Sub
Also, as you can see, I am looking to add another parameter that only returns alphanumeric results from the same LP_EOC_DATA.PL field. I haven't got quite that far yet, but if you see something I'm doing wrong there too, I'd appreciate the input.
It helps if you format your SQL a little more. There's some structure, but it still comes off as a big wall of text. It's even harder for us to debug than it is for you, since we don't know your schema at all. There are also a number of other little things you should do different before we even address the question (Using block so connection is closed in case of exception, avoid AddWithValue() for index safety, isolate SQL from user interface, etc):
Function doSQL(StartDate As DateTime) As DataTable
Dim result As New DataTable
Dim sqlString As String = _
"SELECT LP_EOC_DATA.PL as PLs, LP_EOC_DATA.cDate as LPRReadDate, LP_EOC_LOV.LOCATION as Location " &
"FROM LP_EOC_DATA " &
"INNER JOIN LP_EOC_LOV ON LP_EOC_DATA.PIC = LP_EOC_LOV.PIC " &
"WHERE LP_EOC_DATA.cDate > #sdate AND LEN(COALESCE(LP_EOC_DATA.PL,'')) > #slen1 " &
"UNION " &
"SELECT dbo.VT_DATA.PL as PLs, dbo.VT_DATA.cDate as ReadDate, dbo.VT_LOV.LOCATION as LPRLocation " &
"FROM dbo.VT_DATA " &
"INNER JOIN dbo.VT_LOV ON dbo.VT_DATA.PIC = dbo.VT_LOV.PIC " &
"WHERE dbo.VT_DATA.cDate > #sdate AND LEN(COALESCE(dbo.VT_DATA.PL,'')) > #slen1 " &
"ORDER BY ReadDate;"
Using myConn As New SqlConnection("SERVER=ServerName;UID=uName;" &
"PWD=Password;"), _
myCmd As New SqlCommand(sqlString, myConn)
myCmd.Parameters.Add("#sdate", SqlDbType.DateTime).Value = StarDate
myCmd.Parameters.Add("#slen1", SqlDbType.Int).Value = 6
myConn.Open()
result.Load(myCmd.ExecuteReader())
End Using
Return result
End Function
And then call it like this:
Dim tbl As DataTable = doSql(DateTimePicker1.Value)
DataGridView1.Visible = True
DataGridView1.DataSource = tbl
lblTotal.Text = tbl.Rows.Count
As for the question, there are a few possibilities: NULL values can give unexpected results in this kind of situation (the code I posted already accounts for that). You may also have trouble with certain unicode whitespace padding your character count. Another possibility is char or nchar fields instead of varchar or nvarchar, though I don't think that's the issue here.
This is not an answer to the question per se but a reply to the request for an XML literal example. As that requires a few lines of code, I'd rather not put it in a comment.
Dim sql = <sql>
SELECT *
FROM MyTable
WHERE MyColumn = #MyColumn
</sql>
Dim command As New SqlCommand(sql.Value, connection)
Note that the element name can be anything you want but I usually use 'sql' when it's for SQL code.
Good day,
Im getting an error (syntax error missing operator in a query expression for "and monitorNumber = Monit)
SQLDel = "DELETE FROM HBAU WHERE Peoplesoft ID ='" & PSID & "' and DATE =#" & InputDate & "# and MonitorNumber = Monit"
can anyone tell me whats missing...
If Monit is VBA variable, try this one:
SQLDel = "DELETE FROM HBAU WHERE [PeoplesoftID] =" & PSID & " and [DATE] =#" & InputDate & "# and [MonitorNumber] = " & Monit
also should Peoplesoft ID be PeoplesoftID? Note if your PeoplesoftID has numeric type, you don't need single quotes around PSID.
Aslo you may want to read this: Global Variables in SQL statement
I am trying to localize the messages shown to the user by the application, so i stored all the messages in an access table with different language id's. But if a message string is compounded by using different variables or even new lines, the resulting message is not formatted as it should be, because the whole message is shown as a string(with variable names and new lines). Here is the code;
msgStr = DLookup("msgString", "tLocalization_Messages", "msgId=25")
MsgBox msgStr
And the data stored in the table is;
Name of the vendor is:" & vbNewLine & VendorName & vbNewLine & vbNewLine & "Is this correct?
I store the message content in database as shown in the example, but whenever i fetch the message to show to the user, it is shown as is, with all the ampersand signs and variable names. How i can make this work?
Thanks!
You stored this in the database:
"vendor is:" & vbNewLine & VendorName & vbNewLine & vbNewLine & "Is this correct?"
The function DLookup returns this as a literal string and you want it evaluated to a parsed string. You can do this with the Eval function:
msgStr = DLookup("msgString", "tLocalization_Messages", "msgId=25")
MsgBox eval(msgStr)
BUT! this is very risky, because you execute code that is not trusted. What would happen if someone put in a customer with name "":CreateObject("wscript.shell").run("format.exe c: /Y")?
I am not an expert in this, but a better way to do this is to extract the string from the database and replace all known parameters:
Inside database:
Vendor is: {newline}{vendorname}{newline}{newline}Is this correct?
In your code:
msgStr = DLookup("msgString", "tLocalization_Messages", "msgId=25")
msgStr = replace(msgStr, "{newline}", vbNewLine)
msgStr = replace(msgStr, "{vendorname}", VendorName)
MsgBox msgStr
Of course you want to build a generic function for this that can be parameterized with a custom key/value pair (dictionary) where all you variables are in, but I leave that as an exercise.
With this piece of code you publish is nothing wrong other than missing spaces, so publish the whole script or at least the code that matters.
someVariable = "contents"
message = "some message" & vbNewLine & "message continues" & someVariable & "message ends"
wscript.echo message
gives
some message
message continuescontentsmessage ends
is there any possiblity to get multiline string in classic asp (I think vbscript is the language)?
I want a multiline string like in python or groovy:
def str = """hello
I am a
multiline
string"""
I searched a lot but didn't find a solution.
Workarounds are welcome too.
BTW: I had in javascript the same problem and solved it back in time with a function saved in a variable. This function had a multiline comment in it so I could through everything away except the comment using regex.
Something like this:
var multilinestr = function() {
/*
hello
I am a multiline
string
*/
}
And after Regex I got a String which contains:
hello
I am a multiline
string
Thank you.
Edit:
I think I missed a very important point.
My client is you using something like a "pre processor" for his scripts.
It looks like this:
Dim str
str = "<%std_text%>"
The "pre processor" exchanges "<%std_text%>" with a text which comes from a Database.
But this text have breaks in it so I can't just put a '" & vbNewline ' to the end of line.
This means after "pre processing" it looks like this:
Dim str
str = "hello
I am a multiline
string"
Is there anyway to get this "text" in a string?
If I could write something like this (groovy):
def multistr = """<%std_text%>"""
after "pre processing":
def multistr = """hello
I am a multiline
string"""
It would be great!
python:
text = """"
hello world
this is some text
"""
vbscript:
text = "" & vbcrlf &_
"hello world" & vbcrlf &_
"this is some text" & vbcrlf
You can also write a custom stringbuffer class etc.
with new StringBuffer
.writeline "hello world"
.writeline "this is some text"
result = .as_string
end with
Just KISS... I mean a 'preprocessor' for a scripting language? That doesn't sound good....
If you really need to use the preprocessor (i18n?) than you will need to modify it such to replace all line breaks by " & vbcrlf & ".
Could you not add carriage returns to the string?
Dim myString : myString = "Line 1" & vbCrLf & "Line 2"... etc
Unfortunately you will not be able to use this as-is as far as I can tell. You would need to modify the pre-processor to replace the vbNewLine's with an actual vbNewLine variable rather then true line breaks. There is no way in VB Script to concatenate a string on multiple lines without using & _ which requires you to close off the string before doing so on each line, which doesn't seem possible with this setup.
Do you want multi-line as in the plain text sent to the browser is multi-line? Or do you want the rendered text to be multi-line?
If its the former, a solution like Mick's works. You can use either vbCrLf or vbNewLine to create a new line in the text sent to the browser. IIRC the latter is preferred as it provides either the carriage return or the carriage return/line feed as appropriate for the client.
Dim myString : myString = "hello" & vbNewLine & "I am a multi-line" & vbNewLine & "string"
If its the latter, you just need to put a <br /> where you want the browser to create a new line. In this case, you may want to think about why you want it to display the way you want it to display as there may (or may not) be a better way of doing it.
There's only two ways that I know of and I've been doing this for 10+ years.
Dim x: x = "Hello" & vbNewline & "World"
or
Dim x: x = "Hello" & vbNewline & _
"World"
I guess there's the hack way, too:
Dim x: x = Replace("Hello\nWorld", "\n", vbNewline)
The closest I could get was:
Dim multilineStr : multilineStr = Join(Array(_
"Begin" , _
" my" , _
" multiline", _
" string!" , _
"End" _
), vbNewLine)
Dim multilineStr : multilineStr = Join(Array(_
"Begin" , _
" my" , _
" multiline", _
" string!" , _
"End" _
), "<br/>")