I am trying to build a blank SQL connection in Excel that will be updated with a connection string and command text a later point in the report.
Code I am trying to use:
Workbooks("WorkBook1.xlsm").Connections.Add2 "Test1", "Test1", " ", " ", "SQL"
Syntax from Microsoft:
Add2 (string Name, string Description, object ConnectionString, object CommandText, object lCmdtype, object CreateModelConnection, object ImportRelationships);
However, I am struggling with the syntax as I keep getting errors.
Any ideas?
So this isn't really an answer but rather a work around.
Sub Add_Connection()
Workbooks("WorkBook1.xlsm").Connections.AddFromFile _
"C:\Document\template_Connection.odc"
With ActiveWorkbook.Connections("template")
.Name = "Facility"
.Description = ""
End With
End Sub
I have a saved connection on my computer that I add and rename.
I have two questions:
1. If we can pass an array to VBSCript using java. I am able to pass single variables to VBSCript using following command
Runtime.getRuntime().exec("wscript openChartsDevice.vbs " + fileName + " " + range);
But when I pass a String array, it says type mismatch. I am catching the array passed in
Dim arr()
any Suggestions?
Edit 1 Following question has been answered
2. I am using following Vbscript to create chart in excel
Dim oExl,excelPath,objWriteSheet,objWriteWorkbook
Dim oMychartProcs
Set oExl=CreateObject("Excel.Application")
Set objWriteWorkbook = oExl.Workbooks.Open("SomeExcelfile.xlsx")
Set objWriteSheet = objWriteWorkbook.Worksheets(1)
Set oMychartProcs = objWriteWorkbook.Charts.Add
oMychartProcs.SetSourceData objWriteSheet.Range(Cells(2,1),Cells(7,6))
oMychartProcs.ChartType = 4
oMychartProcs.Name = "ChartName"
oMychartProcs.Activate
I have given the range as A2:F7. when I enter
oMychartProcs.SetSourceData objWriteSheet.Range("A2:F7")
the chart is created perfectly but when I use the
Range(Cells(2,1),Cells(7,6))
whole excel sheet is converted to chart.
I want to provide the range through parameters so I want above formula to work. I've searched a lot and could not find a definitive way for it. Thank you.
You can not pass array as an object. But you can pass its elements as string parameters to the vbscript function with a space as the delimiter.
openChartsDevice.vbs " + fileName + " " + arg[0] + " " + arg[1] + " " + arg[2].....
You can a create a method in java to pass an array and return a string
arg[0] + " " + arg[1] + " " + arg[2].....
Another Approach: Create a file with input parameters. Update your VBScript to refer to that input file to get the parameters instead of looking for command line arguments.
I don't know JScript. But the way to get in VBScript the same thing.
For Each thing in Array()
A = A & thing & " "
Next
You are actually asking how to turn an array into a delimited string not a vbscript array.
See this article which your question title implies you are interested in.
http://blogs.msdn.com/b/ericlippert/archive/2003/09/22/53061.aspx
I am trying to create a range in a function but the range varies so I am going to pass in the definition as a string but I am running into an error because it says it "Expected an array". So, I thought this was because the double quotes weren't included so I tried to include them in the string by doubling up on double quotes but now VBA is saying I have an invalid character in that string (that being the first dollar sign). I am really confused on how to fix this. Any help would be greatly appreciated.
gRange = ""$A$1:$F$2""
Whenever I have issues in VBA with extra quotes in strings, I always fall back on using Chr(34) to replace.
gRange = Chr(34) & "$A$1:$F$2" & Chr(34)
Chr() MSDN Reference
I found a solution using an if Statement like so:
If sheetName = "Totals" Then
ChartData.ActiveSheet.ListObjects("Table1").Resize Range("$A$1:$F$2")
Else
ChartData.ActiveSheet.ListObjects("Table1").Resize Range("$A$1:$G$2")
End If
Instead of using a string.
I'm trying to extract my parameters from my SQL query to build my xml for an SSRS report. I want to be able to copy/paste my SQL into Excel, look through the code and find all instances of '#' and the appropriate parameter attached to it. These paramaters will ultimately be copied and pasted to another sheet for further use. So for example:
where DateField between #FromDate and #ToDate
and (BalanceFiled between #BalanceFrom and #BalanceTo
OR BalancdField = #BalanceFrom)
I know I can use Instr to find the starting position of the first '#' in a line but how then do I go about extracting the rest of the parameter name (which varies) and also, in the first two lines of the example, finding the second parameter and extracting it's variable lenght? I've also tried using the .Find method which I've been able to copy the whole line over but not just the parameters.
I might approach this problem like so:
Remove characters that are not surrounded by spaces, but do not
belong. In your example, the parentheses need to be removed.
Split the text using the space as a delimiter.
For each element in the split array, check the first character.
If it is "#", then the parameter is found, and it is the entire value in that part of the array.
My user-defined function looks something like this:
Public Function GetParameters(ByRef rsSQL As String) As String
Dim sWords() As String
Dim s As Variant
Dim sResult As String
'remove parentheses and split at space
sWords = Split(Replace(Replace(rsSQL, ")", ""), "(", ""), " ")
'find parameters
For Each s In sWords
If Left$(s, 1) = "#" Then
sResult = sResult & s & ", "
End If
Next s
'remove extra comma from list
If sResult <> "" Then
sResult = Left$(sResult, Len(sResult) - 2)
End If
GetParameters = sResult
End Function
Is there a way to have multiline strings in VB.NET like Python
a = """
multi
line
string
"""
or PHP?
$a = <<<END
multi
line
string
END;
Of course something that is not
"multi" & _
"line
You can use XML Literals to achieve a similar effect:
Imports System.XML
Imports System.XML.Linq
Imports System.Core
Dim s As String = <a>Hello
World</a>.Value
Remember that if you have special characters, you should use a CDATA block:
Dim s As String = <![CDATA[Hello
World & Space]]>.Value
2015 UPDATE:
Multi-line string literals were introduced in Visual Basic 14 (in Visual Studio 2015). The above example can be now written as:
Dim s As String = "Hello
World & Space"
MSDN article isn't updated yet (as of 2015-08-01), so check some answers below for details.
Details are added to the Roslyn New-Language-Features-in-VB-14 Github repository.
VB.Net has no such feature and it will not be coming in Visual Studio 2010. The feature that jirwin is refering is called implicit line continuation. It has to do with removing the _ from a multi-line statement or expression. This does remove the need to terminate a multiline string with _ but there is still no mult-line string literal in VB.
Example for multiline string
Visual Studio 2008
Dim x = "line1" & vbCrlf & _
"line2"
Visual Studio 2010
Dim x = "line1" & vbCrlf &
"line2"
I used this variant:
Dim query As String = <![CDATA[
SELECT
a.QuestionID
FROM
CR_Answers a
INNER JOIN
CR_Class c ON c.ClassID = a.ClassID
INNER JOIN
CR_Questions q ON q.QuestionID = a.QuestionID
WHERE
a.CourseID = 1
AND
c.ActionPlan = 1
AND q.Q_Year = '11/12'
AND q.Q_Term <= (SELECT CurrentTerm FROM CR_Current_Term)
]]>.Value()
it allows < > in the string
Multi-line strings are available since the Visual Studio 2015.
Dim sql As String = "
SELECT ID, Description
FROM inventory
ORDER BY DateAdded
"
You can combine them with string interpolation to maximize usefullness:
Dim primaryKey As String = "ID"
Dim inventoryTable As String = "inventory"
Dim sql As String = $"
SELECT {primaryKey}, Description
FROM {inventoryTable}
ORDER BY DateAdded
"
Note that interpolated strings begin with $ and you need to take care of ", { and } contained inside – convert them into "", {{ or }} respectively.
Here you can see actual syntax highlighting of interpolated parts of the above code example:
If you wonder if their recognition by the Visual Studio editor also works with refactoring (e.g. mass-renaming the variables), then you are right, code refactoring works with these. Not mentioning that they also support IntelliSense, reference counting or code analysis.
Multiline string literals are introduced in Visual Basic 14.0 - https://roslyn.codeplex.com/discussions/571884
You can use then in the VS2015 Preview, out now - http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs (note that you can still use VS2015 even when targeting an older version of the .NET framework)
Dim multiline = "multi
line
string"
VB strings are basically now the same as C# verbatim strings - they don't support backslash escape sequences like \n, and they do allow newlines within the string, and you escape the quote symbol with double-quotes ""
this was a really helpful article for me, but nobody mentioned how to concatenate in case you want to send some variables, which is what you need to do 99% of the time.
... <%= variable %> ...
Here's how you do it:
<SQL>
SELECT * FROM MyTable WHERE FirstName='<%= EnteredName %>'
</SQL>.Value
Well, since you seem to be up on your python, may I suggest that you copy your text into python, like:
s="""this is gonna
last quite a
few lines"""
then do a:
for i in s.split('\n'):
print 'mySB.AppendLine("%s")' % i
# mySB.AppendLine("this is gonna")
# mySB.AppendLine("last quite a")
# mySB.AppendLine("few lines")
or
print ' & _ \n'.join(map(lambda s: '"%s"' % s, s.split('\n')))
# "this is gonna" & _
# "last quite a" & _
# "few lines"
then at least you can copy that out and put it in your VB code. Bonus points if you bind a hotkey
(fastest to get with:Autohotkey) to do this for for whatever is in your paste buffer. The same idea works well for a SQL formatter.
Multi-line string literals in vb.net using the XElement class.
Imports System.Xml.Linq
Public Sub Test()
dim sOderBy as string = ""
dim xe as XElement = <SQL>
SELECT * FROM <%= sTableName %>
<ORDER_BY> ORDER BY <%= sOrderBy %></ORDER_BY>
</SQL>
'** conditionally remove a section
if sOrderBy.Length = 0 then xe.<ORDER BY>.Remove
'** convert XElement value to a string
dim sSQL as String = xe.Value
End Sub
To me that is the most annoying thing about VB as a language.
Seriously, i once wrote the string in a file and wrote code something along the lines of:
Dim s as String = file_get_contents("filename.txt")
just so i could test the query directly on SQL server if i need to.
My current method is to use a stored procedure on the SQL Server and just call that so i can pass in parameters to the query, etc
I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.
You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.
Dim script As String = <code><![CDATA[
<script type="text/javascript">
var URL = ']]><%= domain %><![CDATA[/mypage.html';
</script>]]>
</code>.value
You could (should?) put the string in a resource-file (e.g. "My Project"/Resources) and then get it with
Dim a = My.Resources.Whatever_you_chose
Disclaimer: I love python. It's multi-line strings are only one reason.
But I also do VB.Net, so here's my short-cut for more readable long strings.
Dim lines As String() = {
"Line 1",
"Line 2",
"Line 3"
}
Dim s As String = Join(lines, vbCrLf)
you can use XML for this like
dim vrstr as string = <s>
some words
some words
some
words
</s>
in Visual studio 2010 (VB NET)i try the following and works fine
Dim HtmlSample As String = <anything>what ever you want to type here with multiline strings</anything>
dim Test1 as string =<a>onother multiline example</a>
Available in Visual Basic 14 as part of Visual Studio 2015
https://msdn.microsoft.com/en-us/magazine/dn890368.aspx
But not yet supported by R#. The good news is they will be supported soon! Please vote on Youtrack to notify JetBrains you need them also.
If you need an XML literal in VB.Net with an line code variable, this is how you would do it:
<Tag><%= New XCData(T.Property) %></Tag>
Since this is a readability issue, I have used the following code:
MySql = ""
MySql = MySql & "SELECT myTable.id"
MySql = MySql & " FROM myTable"
MySql = MySql & " WHERE myTable.id_equipment = " & lblId.Text
You can also use System.Text.StringBuilder class in this way:
Dim sValue As New System.Text.StringBuilder
sValue.AppendLine("1st Line")
sValue.AppendLine("2nd Line")
sValue.AppendLine("3rd Line")
Then you get the multiline string using:
sValue.ToString()
Use vbCrLf or vbNewLine. It works with MessageBoxes and many other controls I tested.
Dim str As String
str = "First line" & vbCrLf & "Second line"
MsgBox(str)
str = "First line" & vbNewLine & "Second line"
MsgBox(str)
It will show two identical MessageBoxes with 2 lines.
No, VB.NET does not yet have such a feature. It will be available in the next iteration of VB (visual basic 10) however (link)
if it's like C# (I don't have VB.Net installed) you can prefix a string with #
foo = #"Multiline
String"
this is also useful for things like #"C:\Windows\System32\" - it essentially turns off escaping and turns on multiline.