Working in VBA, I cannot assign a string to an initlialized string variable (compiling error: expected end of statement)

StackOverflow https://stackoverflow.com//questions/24039148

Question

I am working in a module in access trying to initialize variables. For some reason the declaration:

Dim ModName As String = "modWindowsFileSystem" 

creates a compiling error at the '=' with the error message "Expected:end of statement". I have looked up the format on mutiple websites that all agree with my syntax here is a trustworthy one: http://msdn.microsoft.com/en-us/library/7ee5a7s1.aspx Another website suggested I declare the variable within a function such as

Sub AssignValueString()
   Dim Modname As String
   Modname = "modWindowsFileSystem"
End Sub

but that seems unnecessary. One issue that may be considered is I have saved the module and named it modWindowsFileSystem. I am not sure if this will conflict somehow with initializing that variable.

Was it helpful?

Solution

VBA is a little different from VB. The msdn link you posted is actually for VB, which allows for inline declarations and assignment. VBA won't allow this, unfortunately.

So, you can either split them, like your example:

Dim Modname As String
Modname = "modWindowsFileSystem"

Or, you can place the continuation character : to achieve this on one line.

Dim Modname As String : Modname = "modWindowsFileSystem"

As far as the assignment for a module's variables, you can declare global variables outside of a function, but you would need to set their value within a function, like an init() function. Constants (labelled with Const) can be declared and assigned outside of a function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top