Tag Archives: Visual Basic

Instruct T4 to use C# v3.5

Consider this simple T4 template:

<# for (var i = 0; i < 10; ++i) { WriteLine("hello"); } #>

Trying to build the project results in a compilation error because ‘var’ is an unknown type. A bit of research learned me that i should instruct the processor to use a specific c# version like this:

<#@ template language="C#v3.5" inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation"  #>
<# for (var i = 0; i < 10; ++i) { WriteLine("hello"); } #>

Problem solved :)

Access a control by name

I know a mathematician that can do magic with stats. That’s also the reason why he works at Eurostat. He’s automating a lot of his work by programming in Visual Basic for Applications. He asked me if i wanted to look at his code because he had the feeling there was a smell. Here are a couple lines:

With SomeForm
 .txtJanvier60.Value = vaData1(1, 2)
 .txtFevrier60.Value = vaData1(1, 3)
 .txtJanvier61.Value = vaData1(1, 2)
 .txtFevrier61.Value = vaData1(1, 3)
 ...
 .txtJanvier70.Value = vaData1(1, 2)
 .txtFevrier70.Value = vaData1(1, 3)
End With

It took me 5 minutes to search the web and change his code as following:

Dim months(1) as String
months(0) = "Janvier"
months(1) = "Fevrier"

With SomeForm
 For i = 60 to 70
  For j = 0 to UBound(months)
   .Controls("txt" & months(j) & CStr(i)).Value = vaData1(1, j + 2)
  Next j
 Next i
End With

Removing selected items from a ListBox

Today i was experimenting with a couple of windows controls. For some reason i wasn’t able to remove the selected items from a ListBox. Here is the code that didn’t work:

For Each index As Integer = ListBox1.SelectedIndices
  ListBox2.Items.Add(ListBox1.Items(index))
  ListBox1.Items.Remove(index)
End For

The problem is that when you remove an item from the collection the indices change. Here is a possible solution:

Dim index As Integer = ListBox1.SelectedIndex
While index <> -1
  ListBox2.Items.Add(ListBox1.Items(index))
  ListBox1.Items.Remove(index)
  index = ListBox1.SelectedIndex
End While