I have problem Concatenate with "&" and two value VBA excel - vba

I have problem with this code, it's showing me an error
, why is this wrong?
dim aData as Variant
dim TBNumV as Long
eRows as Long
aData.value="433-333-"
TBNumV.value=0635
eRows=15
Range(eRows, 2).Value = aData.Value & TBNumV.Value

If you write something with a dot, you are referring to a method or property of an object. A Range is an object and has (among others) a property Value (is has also other properties like Font, Address, Interior...).
A simple variable like a Long is not an object in VBA, it has no properties, you simply write TBNumV = 0635.
A special case it the Variant, a Variant can be anything, depending on how you use it. You could assign an object to a variant variable (but you don't do in your code). You use it as a simple variable and want to assign a string to it: aData = "433-333-". You could consider to declare aData as String, use Variant only if you really need to.
Then you have a syntax error declaring eRows, the Dim-statement is missing.
And your syntax for Range is wrong. Either write Range("B" & eRows) or you can use Cells(eRows, 2).
Dim aData As Variant
Dim TBNumV As Long
Dim eRows As Long
aData = "433-333-"
TBNumV = 635
eRows = 15
Cells(eRows, 2).Value = aData & TBNumV

Related

Excel vba: constant expression required in for cycle

I have a function that returns a Dictionary with pairs key-value. Then I proceed to use on such pair to create an array: I get a value for key "DATA_ITEMS_NUMBER" to determine arrays' max length. However it results in an error...
Function getGlobalVariables()
Dim resultDict As Object
Set resultDict = CreateObject("Scripting.Dictionary")
resultDict.Add "DATA_ITEMS_NUMBER", _
ThisWorkbook.Worksheets("setup").Cells(25, 5).value
Set getGlobalVariables = resultDict
End Function
Function getBudgetItemInfos(infoType As String, year As Integer)
Dim globals As Object
Set globals = getGlobalVariables()
Dim DATA_ITEMS_NUMBER As Integer
DATA_ITEMS_NUMBER = globals("DATA_ITEMS_NUMBER")
Dim resultArray(1 To DATA_ITEMS_NUMBER) As String
...
End Function
The Dim statement isn't executable; you can't put a breakpoint on a Dim statement, it "runs" as soon as the local scope is entered, in "static context", i.e. it doesn't (and can't) know about anything that lives in "execution context", like other local variables' values.
Hence, Dim foo(1 To SomeVariable) is illegal, because SomeVariable is not a constant expression that's known at compile-time: without the execution context, SomeVariable has no value and the array can't be statically sized.
If you want a dynamically-sized array, you need to declare a dynamic array - the ReDim statement is executable:
ReDim resultArray(1 To DATA_ITEMS_NUMBER) As String
Note that a Dim resultArray() statement isn't necessary, since ReDim is going to perform the allocation anyway: you won't get a "variable not declared" compile-time error with a ReDim foo(...) without a preceding Dim foo and Option Explicit specified.
For good form your Function procedures should have an explicit return type though:
'returns a Scripting.Dictionary instance
Function getGlobalVariables() As Object
And
'returns a Variant array
Function getBudgetItemInfos(infoType As String, year As Integer) As Variant
Otherwise (especially for the Object-returning function), you're wrapping your functions' return values in a Variant, and VBA needs to work harder than it should, at the call sites.

Using a variable as a sheet name

I am getting a RunTime 13 error when trying to use a variable for a sheetname as per below:
Sub inputdata()
Set asheet1 = ThisWorkbook.Worksheets("input").Range("D12")
Set rangeDate = ThisWorkbook.Worksheets("input").Range("inputdate")
Range("F12:M12").Copy
Sheets(asheet1).Select
It is erroring on the line Sheets(asheet1).Select
Any help would be great thanks!
The asheet1 is not a string, you are asigning a range object to it . You should declare asheet1 as string and the change this line to
Dim asheet1 as string
asheet1 = ThisWorkbook.Worksheets("input").Range("D12").Value
That should make it work!
Edit
removed the Set keyword from the string var.
Option Explicit
Sub inputdata()
dim inputSheet as WorkSheet
dim aCellOnInputSheet as Range
dim inputDateCell as Range
dim userSheetName as String
Set inputSheet = ThisWorkbook.Worksheets("input")
Set aCellOnInputSheet = inputSheet.Range("D12")
userSheetName = aCellOnInputSheet.Value
Set inputDateCell = inputSheet.Range("inputdate")
Range("F12:M12").Copy
Sheets(userSheetName).Select
End Sub
EDIT: A couple of points
1) Option Explicit is a must.
2) Define variables and name it appropriately. i.e. define variable which refers to a cell/Range with the name range instead of aSheet - it confuses the reader

How to pass a dynamic array into a VBA object. Compile error: Invalid use of property

I'm trying to pass an array into a custom class for storage and further use within that object. The class object has the following definition:
' Class Name: MBRMCurves
Implements ICurves
Private m_lInterpDates() As Long
Public Property Get InterpDates() As Long()
InterpDates = m_lInterpDates
End Property
Public Property Let InterpDates(lInterpDates() As Long)
m_lInterpDates = lInterpDates
End Property
The module that calls this code looks like this:
Dim objResult As New MBRMCurves
'Store the forward prices
Dim fx_fwd() As Double
'Store the interpolation dates
Dim int_dates() As Long
'initially there are no people
Dim NumberTenors As Integer
NumberTenors = 0
Dim cell As range
' Create ranges of Dates
Dim range As range
Dim range_topcell As range
' TODO Pri1 Create the Curves Obj
With Worksheets("test")
' Populate the dates of the FWD rates.
Set range_topcell = .range("B5")
Debug.Print range_topcell.Value
Set range = .range(range_topcell, range_topcell.End(xlDown))
Debug.Print range.Count
' Add more columns to the FWD array
ReDim fx_fwd(0 To range.Count - 1, 0 To 3)
ReDim int_dates(0 To range.Count - 1)
' Set the counter
NumberTenors = 0
' Populate the dates of the FWD rates into the first column of the dates array.
For Each cell In range
NumberTenors = NumberTenors + 1
int_dates(NumberTenors - 1) = cell.Value
Next cell
' Add interpolation dates to Curves object
objResult.InterpDates int_dates
The last line in the above code is giving me the compile error: Invalid use of property.
I believe that the syntax of me Let function is correct, but I might be missing a more subtly nuanced oversight.
Can anyone see what I'm doing wrong? I'm working with Excel 2003 and VBA 6.5 on Windows XP.
Any suggestions would be greatly appreciated.
Thanks,
Christos
a property is not a method call and you need to set it equal to your array:
objResult.InterpDates = int_dates
There still might be an issue with the array your passing in but this is a first step.

Why can't I pass a String variable into VBA's Range function?

I'm trying to dynamically transpose a Recordset over a Range in Excel using VBA. I can do the transposition succesfully when I give it a static range such as this:
Range("A1:C16").Select
Range("A1:C16").Value = Application.WorksheetFunction.Transpose(scores)
When I try to use an equivalent string and pass it in to the Range function, however, it fails. My variable trange when printed out is "A1:C16" (including the double quotes). The reason I need to pass it a string is because the string is derived from a length variable which could be any value.
This code below fails:
Dim trange As String
trange = """A1:C" & slength & """"
MsgBox (trange)
Range(trange).Select
Range(trange).Value = Application.WorksheetFunction.Transpose(scores)
Unfortunately, escaping double quotes in VBA is ugly and that's why my trange assignment expression looks strange but when I MsgBox it, it is in fact giving me the correct value.
When you use the code Range("A1:C16").Select, the quotes are not part of the string, but simply delineate it. Therefore, you don't need to insert quotes into the string you're creating by escaping them. The following test case works for me:
Dim trange As String
Dim slength As Integer
slength = 5
trange = "A2:C" & slength
MsgBox (trange)
Range(trange).Select
Range(trange).Value = 5
Using string concatenation to construct range addresses is a bad idea. It's messy and error-prone (as your example illustrates!).
Instead of Range("A1:C16"), you can say any of the following:
Range("A1").Resize(16, 3)
Cells(1, 1).Resize(16, 3)
Range(Cells(1, "A"), Cells(16, "C"))
Range(Cells(1, 1), Cells(16, 3))
There are probably more possibilities. The key is that none of them involve string concatenation.
Replace 16 by slength in any of the examples above to make your variable-size range.
Also, it's good practice specify what worksheet you're referring to. Instead of plain Range(anything), use e.g.
Sheet1.Range(anything)
Worksheets("Sheet1").Range(anything)
or even better,
With Sheet1
.Range(anything)
' other stuff on Sheet1
End With

Can I simultaneously declare and assign a variable in VBA?

Can I convert the following declaration and assignment into one line:
Dim clientToTest As String
clientToTest = clientsToTest(i)
or
Dim clientString As Variant
clientString = Split(clientToTest)
There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the : continuation character if you want it on one line for readability;
Dim clientToTest As String: clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)
Hint (summary of other answers/comments): Works with objects too (Excel 2010):
Dim ws As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"
You can sort-of do that with objects, as in the following.
Dim w As New Widget
But not with strings or variants.
You can define and assign a value in one line, as shown below. I have given an example of two variables declared and assigned in a single line. If the data type of multiple variables are the same:
Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946
in fact, you can, but not that way.
Sub MySub( Optional Byval Counter as Long=1 , Optional Byval Events as Boolean= True)
'code...
End Sub
And you can set the variables differently when calling the sub, or let them at their default values.
In some cases the whole need for declaring a variable can be avoided by using With statement.
For example,
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogSaveAs)
If fd.Show Then
'use fd.SelectedItems(1)
End If
this can be rewritten as
With Application.FileDialog(msoFileDialogSaveAs)
If .Show Then
'use .SelectedItems(1)
End If
End With