excel,vba,excel-vba,excel-2010 , VBA “Compile Error: Statement invalid outside Type Block”


VBA “Compile Error: Statement invalid outside Type Block”

Question:

Tag: excel,vba,excel-vba,excel-2010

I am running a VBA Macro in Excel 2010 with tons of calculations, so data types are very important, to keep macro execution time as low as possible.

My optimization idea is to let the user pick what data type all numbers will be declared as (while pointing out the pros and cons of each data type, the balance between accuracy/flexibility and CPU intensiveness/macro execution time). However, when I run the macro, I get the following error message:

Compile error:

Statement invalid outside Type block

Here is the offending portion of the code:

Ind2 As Double, BgrValP As Double, BgrRow As Double, M40eff As Double

Here is the relevant part of the macro:

' Develop fake data to at glance recognize whether program works.
' Source http://www.cpearson.com/excel/optimize.htm
Option Explicit

Private Sub Function1()
On Error GoTo ErrorHandler
Dim userChoice As Variant
Dim strPath As String, strFileN As String, strDirN As String, strRangeNOut As String, strRangeNIn As String, strFilename As String, strTLCorn As String, strBRCorn As String, strSelectedFile As String, strtemp_name As String
Dim lngCount As Long
Dim vResMatrix(), vCPath, vFileN As Variant

'   MEeff = measure of efflux due to crudely purified HDL in scintillation
'   https://msdn.microsoft.com/en-us/library/ae55hdtk.aspx

'   Give the user macro options based on how fast or slow the computer is
userChoice = MsgBox("This macro by default treats all numbers as doubles for maximum precision. If you are running this macro on an old computer, you may want to redeclare numbers as singles, to speed up the macro." & vbNewLine & "You can also use integers for a quick estimate of data results.")

If userChoice = "Double" Then
    Dim RangeNOut As Double, vRangeNIn As Double, Ind6 As Double, Ind4 As Double, Ind5 As Double
    Dim Step2 As Double, MRow As Double, ColIn As Double, Ind3 As Double, Mcol As Double
    Dim MxRNo As Double, BgrSum As Double, RowIn As Double, Ind As Double, M40eff As Double, Step As Double
    Dim ColNo As Double, Startcol As Double, Startrow As Double, MeanComp As Double
    Dim PlateNo As Double, MonoVal As Double, Ind1 As Double, EntryRow2 As Double, EntryRow As Double
    Ind2 As Double, BgrValP As Double, BgrRow As Double, M40eff As Double
    Dim BrgSum As Double, BgrVal As Double, RangeNIn As Double, RangeNOut As Double, TLCorn As Double
    Dim Volcorr As Double, BRCorn As Double, MEeff As Double, MediaVal As Double

ElseIf userChoice = "Integer" Then
    Dim RangeNOut As Integer, vRangeNIn As Integer, ecInd6 As Integer, Ind4 As Integer, Ind5 As Integer
    Dim Step2 As Integer, MRow As Integer, ColIn As Integer, Ind3 As Integer, Mcol As Integer
    Dim MxRNo As Integer, BgrSum As Integer, RowIn As Integer, Ind As Integer, M40eff As Integer
    Dim Step As Integer, ColNo As Integer, Startcol As Integer, Startrow As Integer, MeanComp As Integer
    Dim PlateNo As Integer, MonoVal As Integer, Ind1 As Integer, EntryRow2 As Integer, EntryRow As Integer
    Dim Ind2 As Integer, BgrValP As Integer, BgrRow As Integer, M40eff As Integer
    Dim BrgSum As Integer, BgrVal As Integer, RangeNIn As Integer, RangeNOut As Integer, TLCorn As Integer
    Dim Volcorr As Integer, BRCorn As Integer, MEeff As Integer, MediaVal As Integer

ElseIf userChoice = "Single" Then
    Dim RangeNOut As Single, vRangeNIn As Single, ecInd6 As Single, Ind4 As Single, Ind5 As Single
    Step2 As Single, MRow As Single, ColIn As Single, Ind3 As Single, Mcol As Single
    Dim MxRNo As Single, BgrSum As Single, RowIn As Single, Ind As Single, M40eff As Single, Step As Single
    Dim ColNo As Single, Startcol As Single, Startrow As Single, MeanComp As Single
    Dim PlateNo As Single, MonoVal As Single, Ind1 As Single, EntryRow2 As Single, EntryRow As Single
    Ind2 As Single, BgrValP As Single, BgrRow As Single, M40eff As Single
    Dim BrgSum As Single, BgrVal As Single, RangeNIn As Single, RangeNOut As Single, TLCorn As Single
    Volcorr As Single, BRCorn As Single, MEeff As Single, MediaVal As Single

Else
    GoTo Function1
    MsgBox("This is not a supported data type: double, single, or integer.", vbCritical, "Unsupported Data Type")

Here is the code I am currently using for this:

Private Sub Function2(ByVal VarType As String)

Dim mVers As String
Dim userChoice As Variant

'   Give the user macro options based on how fast or slow the computer is using advanced conditional compliling
userChoice = MsgBox("This macro by default treats all numbers as doubles for maximum precision. If you are running this macro on an old computer, you may want to relare numbers as singles, to speed up the macro." & vbNewLine & "You can also use integers for a quick estimate of data results.")
userChoice = VarType

#If VarType = "Double" Or "double" Then
    Dim RangeNOut As Double, vRangeNIn As Double, Ind6 As Double, Ind4 As Double, Ind5 As Double
    Dim Step2 As Double, MRow As Double, ColIn As Double, Ind3 As Double, Mcol As Double
    Dim MxRNo As Double, BgrSum As Double, RowIn As Double, Ind As Double, M40eff As Double, Step As Double
    Dim ColNo As Double, Startcol As Double, Startrow As Double, MeanComp As Double
    Dim PlateNo As Double, MonoVal As Double, Ind1 As Double, EntryRow2 As Double, EntryRow As Double
    Dim Ind2 As Double, BgrValP As Double, BgrRow As Double, M40eff As Double
    Dim BrgSum As Double, BgrVal As Double, RangeNIn As Double, RangeNOut As Double, TLCorn As Double
    Dim Volcorr As Double, BRCorn As Double, MEeff As Double, MediaVal As Double
#ElseIf VarType = "Single" Or "single" Then
    Dim RangeNOut As Single, vRangeNIn As Single, ecInd6 As Single, Ind4 As Single, Ind5 As Single
    Step2 As Single, MRow As Single, ColIn As Single, Ind3 As Single, Mcol As Single
    Dim MxRNo As Single, BgrSum As Single, RowIn As Single, Ind As Single, M40eff As Single, Step As Single
    Dim ColNo As Single, Startcol As Single, Startrow As Single, MeanComp As Single
    Dim PlateNo As Single, MonoVal As Single, Ind1 As Single, EntryRow2 As Single, EntryRow As Single
    Dim Ind2 As Single, BgrValP As Single, BgrRow As Single, M40eff As Single
    Dim BrgSum As Single, BgrVal As Single, RangeNIn As Single, RangeNOut As Single, TLCorn As Single
    Dim Volcorr As Single, BRCorn As Single, MEeff As Single, MediaVal As Single
#ElseIf VarType = "Integer" Or "integer" Then
    Dim RangeNOut As Integer, vRangeNIn As Integer, ecInd6 As Integer, Ind4 As Integer, Ind5 As Integer
    Dim Step2 As Integer, MRow As Integer, ColIn As Integer, Ind3 As Integer, Mcol As Integer
    Dim MxRNo As Integer, BgrSum As Integer, RowIn As Integer, Ind As Integer, M40eff As Integer
    Dim Step As Integer, ColNo As Integer, Startcol As Integer, Startrow As Integer, MeanComp As Integer
    Dim PlateNo As Integer, MonoVal As Integer, Ind1 As Integer, EntryRow2 As Integer, EntryRow As Integer
    Dim Ind2 As Integer, BgrValP As Integer, BgrRow As Integer, M40eff As Integer
    Dim BrgSum As Integer, BgrVal As Integer, RangeNIn As Integer, RangeNOut As Integer, TLCorn As Integer
    Dim Volcorr As Integer, BRCorn As Integer, MEeff As Integer, MediaVal As Integer
#Else
    MsgBox "VarType " & VarType & " is not valid. Check spelling."
#End If

'   MEeff = measure of efflux due to crudely purified HDL in scintillation
MsgBox "For additional information about this macro:" & vbNewLine & "1. Go to tab Developer" & vbNewLine & "2. Select Visual Basic or Macro." & vbNewLine & "See the comments or MsgBoxes (message boxes)."

'   Start File Explorer to select file containing data (simple GUI, much easier than coding in the file)

With Application.FileDialog(msoFileDialogOpen)
    .AllowMultiSelect = True
    .Show

'   Display paths of each file selected
    For lngCount = 1 To .SelectedItems.Count
    Next lngCount
    For Each strFilename In .SelectedItems
        MsgBox strFilename
        Function2
    Next
End With

ErrorHandler:
MsgBox "Error detected" & vbNewLine & "Error" & Err.Number & ": " & Err.Description, vbCritical, "Error Handler: Error " & Err.Number
MsgBox "If you want to force the program to run, go to the line below and insert a ' mark to comment the line out." & vbNewLine & "On Error GoTo ErrorHandler", vbCritical, "Error Handler: Error " & Err.Number

End Sub

Answer:

You have:

Dim RangeNOut as Double
Dim RangeNOut as Integer

While the IF statements in there are a nice idea, VBA will not allow you to do that. It doesn't do conditional 'compilation' since it isn't a compiled language. When VBA runs your code, all your variables are declared (no matter where in the code the Dim statement is located), then the code begins executing.

It's a nice idea you've come up with, but attempting this in VBA is like bringing a piece of Silly Putty™ to a gun fight - it's just horribly unequipped for the job.

Also, if you're that concerned about execution speed, VBA isn't your weapon of choice, either. I don't have any stats to back it up off the top of my head, but I doubt you'd actually see much difference in execution speed based on your three different variable types.

To pass the variable type as a parameter to the function, use this:

Private Sub Function1(ByVal VarType as String)

  #If VarType = "Double" then
    ...
  #ELSEIF VarType = "Single" then
    ...
  #ELSEIF VarType = "Integer" then
    ...
  #ELSE
    MsgBox "You passed in a 'VarType' of " & VarType & " - that's not valid"
  #ENDIF

Also, I just noticed that in your final Else you have Goto Function1. I'm not sure what you're trying to accomplish there, but:

  1. Don't use goto. Except in VBA style error handling, it's almost never necessary
  2. You don't have a label defined for the Goto to jump to, anyway.

See also VBA function overloading for another possible option.

Notice: Despite the upvotes and accepted answer status, I tried the following, and it DOES NOT work as requested by OP:

Sub test()
  func "Double"
  func "Single"
  func "Integer"
  func "String"
End Sub

Function func(v As String)
  #If v = "Double" Then
    Dim myvar As Double
    Range("A1") = "MyVar type is: " & vartype(v)
  #ElseIf v = "Single" Then
    Dim myvar As Single
    Range("a2") = "MyVar type is: " & vartype(v)
  #ElseIf v = "Integer" Then
    Dim myvar As Integer
    Range("a3") = "MyVar type is: " & vartype(v)
  #Else
    Range("A4") = "Invalid var type passed: " & v
  #End If

  MsgBox "Passed in " & v

End Function

All calls to Func() end up in the #Else section of code, populating Range("A4") with the Invalid var type passed: text.

Sadly, this will not work.

If it is truly necessary to have functions with different variable types doing the exact same thing, I think the following would be the best bet:

Sub Test()
  Dim VType as String

  While Vtype <> "Integer" and VType <> "Double" and VType <> "Single" and VType <> "Cancel"
    vType = msgBox("Enter variable type")
  Wend

  If VType = "Integer" then
    MyFuncInt()
  ElseIf VType = "Double" then
    MyFuncDouble()
  Elseif VType = "Single"
    MyFuncSingle()
  Else
    MsgBox "Function call cancelled"
  End if
End Sub

Function MyFuncInt()
  Dim AllTheVars as Integer
  ...
End Function

Function MyFuncDouble()
  Dim AllTheVars as Double
  ...
End Function

Function MyFuncSingle()
  Dim AllTheVars as Single
  ...
End Function

Related:


Interface Controls for DoEvent in Excel


excel,vba,excel-vba,loops,doevents
I have a macro to loop through a range and return emails to .Display based on the DoEvents element within my module. I iterate that: row_number = 1 'And Do DoEvents row_number = row_number +1 'Then a bunch of formatting requirements Loop Until row_number = 'some value I am wondering...

Replace reference with its value in Excel VBA workbook


vba,excel-vba
I have an Excel workbook to manage my Delivery Notes, which creates another workbook with actual delivery note and stores it in the folder for me, then places new record in my main workbook so that the Delivery Number for the next delivery note can be increased by 1. My...

Userform is not unloading once command button is pressed


vba,excel-vba
Having a little trouble with my userform, its not unloading once i hit the command button the data is inputted to the sheet but the userform is not refreshed and the data stays in the text boxes. It was working fine until i put the data validation in, but i...

Which is faster in Excel, an if formula giving 1 or 0 instead of true/false or --?


excel
I've got a large spreadsheet that I'm trying to optimise as it has over 12,000 lines of data, with in excess of 28 columns. It currently takes a significant amount of time to execute and I'm therefore starting to pare it down. As part of this I've started looking at...

NoClassDefFoundError: UnsupportedFileFormatException while using apache poi to write to an excel file


java,excel,apache-poi,writing
I am trying to write to an excel(.xlsx) file using Apache poi, I included the apache poi dependencies in my pom.xml file. But I am getting the following exception in execution. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at...

VBA how to initialize vCPath


vba,excel-vba,excel-2010
How do I initialize vCPath? VBA Run-Time Error 1004 @Garry's Student says I "must somehow use the info you get from Application.FileDialog(msoFileDialogOpen) to generate the full filespec of the file you wish to open". What's the simplest way to do this? I am a VBA beginner: I have been programming...

Excel - select a cell based on adjacent cell value


excel
I have the following excel spreadsheet and I am trying to work out how I can write a formula in order to provide the values in column D. In each row, there is a test date, I am trying to calculate the day difference from each test date to the...

How to insert excel formula to cell in Report Builder 3.0


sql-server,excel,reporting-services,excel-formula,ssrs-2008-r2
There is RDL report template for SQL Server Reporting Services. I need to set value for cell in table in the report template which must be calculated from other values in the report. When the report is exported to Excel file I need to see the Excel formula in that...

Using a stored integer as a cell reference


excel,excel-vba,reference
Dim x As Integer Dim y As Integer For y = 3 To 3 For x = 600 To 1 Step -1 If Cells(x, y).Value = "CD COUNT" Then Cells(x, y).EntireRow.Select Selection.EntireRow.Hidden = True End if If Cells(x, y).Value = "CD Sector Average" Then Cells(x, y).EntireRow.Select Selection.Insert Shift:=xlDown Cells(x +...

How do I do to count rows in a sheets with filters? With a suppress lines


excel,vba,filter
I have a sheet with lots of columns, but when I filter and use count = Application.WorksheetFunction.CountA(Range("A:A")) It returns all the rows non Empty. Not only the rows I filtered....

VBA data type to store Range().Characters()


vba
I can't find a data type to store Characters from a Range. I already tried the following code, but nothing happened. I think the problem is because of wrong data type. Dim chars As Characters chars = Range("A2").Characters(0, 4) MsgBox chars.Text ...

If cell value starts with a specific set of numbers, replace data


excel,vba,excel-vba
My cell values are strings of numbers (always greater than 5 numbers in a cell, ie 67391853214, etc.) If a cell starts with three specific numbers (ie 673 in a cell value 67391853214) I want the data in the cell to be replaced with a different value (if 673 are...

EXCEL VBA: How to manupulate next cell's (same row) value if cell.value=“WORD” in a range


excel,vba,excel-vba
I want to change the next cell in same row in a if cell.value="word" in a range. I have defined the range, using 'for' loop. In my code, if cell.value="FOUND THE CELL" then cell.value+1="changed the next right side cell" cell.value+2="changed the second right side cell" end if I know this...

Copying sheet to last row of a sheet from another workbook


excel,vba,excel-vba
I'm stuck in this block of code that copies sheet("Newly Distributed") to the last row of sheet("Source") from another workbook. The error is runtime error 9. What's wrong with my code? Any response would be appreciated. Private Sub copylog3() Dim lRow As Long Dim NextRow As Long, a As Long...

Exit Sub And Call another Sub


vba,excel-vba,call
I have two subs, sub1 and sub2. I want to exit sub1 completely and start sub2 if a condition is satisfied. My attempt is (running from : sub1 . . If x=y Then Exit Sub And Call sub2 End If . . End Sub ...

Identifying cell in Openpyxl


python,excel,openpyxl
I've been working on a project, in which I search an .xlsx document for a cell containing a specific value "x". I've managed to get so far, but I can't extract the location of said cell. This is the code I have come up with: from openpyxl import load_workbook wb...

Converting column from military time to standard time


r,excel
I'm trying to convert a column showing the time of road traffic accidents from military time to standard time. The data looks like this: Col1 Time..24hr. 1 1404 2 322 3 1945 4 1005 5 945 I'd then like to convert to 12hr so for '322' I'd like to make...

12 Characters Including leading and following zeros


excel
I am finding this difficult to explain, but ultimately I am wanting a cells value to be 12 characters long including +/- a decimal point and following zeroes. Examples are 1200 would become +1200.000000 -20 would become -20.00000000 99999999 would become +99999999.00 I have tried FIXED, LENGTH, and formatting rules...

Converting ADODB Loop into DAO


excel,vba,ms-access,ado,dao
Hi I've been developing a vba project with a lot of help from examples here. I'm trying to access a MS Access database from Excel VBA and import large data sets (500-100+ rows) per request. Currently, the following loop works using ADODB however, the Range("").Copyfromrecordset line is taking very long...

Excel VBA Loop Delete row does not start with something


excel,excel-vba
I have some data at work looks like this: 00 some data here... 00 some data here... 00 some data here... 00 some data here... Other data I want to remove Other data I want to remove Other data I want to remove Other data I want to remove 00I...

Comparing cell contents against string in Excel


string,excel,if-statement,comparison
Following is my table file:*.css file:*.csS file:*.PDF file:*.PDF file:*.ppt file:*.xls file:*.xls file:*.doc file:*.doc file:*.CFM file:*.dot file:*.cfc file:*.CFM file:*.CFC file:*.cfc file:*.DOC I need a formula to populate the H column with True or False if it finds column G in column F (exact case). I used following but nothing seems to...

Removing Alert When Using DeleteFile API


vb.net,vba,api,delete
I'm writing a VBA application which involves looping a large number of directories recursively. I am using the FindFirstFile API to to achieve this, as it offers a substantial performance boost over the FileSystemObject. In order to remove the FSO from my code entirely, I need a routine to delete...

Using VLOOKUP formula or other function to compare two columns


mysql,excel,vba,date
I have one table like this: SHORT TERM BORROWING 1/6/2009 94304 12/31/2010 177823 6/30/2011 84188 12/31/2011 232144 6/30/2012 94467 9/30/2012 91445 12/31/2012 128523 3/31/2013 83731 6/30/2013 78330 9/30/2013 70936 12/31/2013 104020 3/31/2014 62345 6/30/2014 62167 9/30/2014 63494 12/31/2014 104239 3/31/2015 69056 I have another column which lists each date from...

excel search engine using vba and filters?


excel,vba
I am using the following vba code to filter my rows in excel based on the value in my cell C5 Sub DateFilter() 'hide dialogs Application.ScreenUpdating = False 'filter for records that have June 11, 2012 in column 3 ActiveSheet.Range("C10:AS30").AutoFilter Field:=1, Criteria1:="*" & ActiveSheet.Range("C5").Value & "*" Application.ScreenUpdating = True End...

VBA “Compile Error: Statement invalid outside Type Block”


excel,vba,excel-vba,excel-2010
I am running a VBA Macro in Excel 2010 with tons of calculations, so data types are very important, to keep macro execution time as low as possible. My optimization idea is to let the user pick what data type all numbers will be declared as (while pointing out the...

Excel-VBA: create named Range in row until end of cell content


vba,excel-vba,range
Imagine an Excel sheet with some rows and some content in each row (i.e. different column-length for each row). In Excel-VBA: How can I create a range-X within column-X that goes from row-cell-2 to the end of the content of this X-column ?? i.e. I would like to create a...

Excel - Pulling data from one cell within a list


excel,powerpoint,spreadsheet
I use PowerPoint as a graphics template to type up football player names and there squad numbers. It can be a long procedure and so far following YouTube tutorials i have managed to create a form in Excel which can update the text boxes in PowerPoint at the click of...

timestamp SQL to Excel


php,mysql,sql,excel
If this is a duplicate, please let me know, I haven't found anything. I have written a php file that can read content from a database table and write it into a excel .xls file. Everything works fine except by that timestamps. In my generated .xls file every timestamp is...

How do you delete favorite folders in outlook using VBA


vba,outlook-2007
I wish to delete all the folders from the outlook favorites then subsequently replace them, but the delete doesn't seem to work. What's wrong with my code. Setup Objects works fine ' Get the "Favorite Folders" navigation group Set favGroup = Application.ActiveExplorer.NavigationPane.Modules.GetNavigationModule(olModuleMail).NavigationGroups.GetDefaultNavigationGroup(olFavoriteFoldersGroup) This works Set inboxFldr = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) favGroup.NavigationFolders.Add (inboxFldr)...

Creating a Range in VBA


vba,range
I'm working on my first VBA function. The goal is to have a function that accepts two integers as inputs, and outputs an array containing all the integers in between the two inputs (end-points included). Example: If I input 5 and 9, the output should be an array of 5,...

Using date in CreateQueryDef


vba,date,ms-access
I have a table on which I run a query that I export to Excel. Here is an example: Table: Food Item | Price | Limit_Date | ------------------------------- Carrot | 0.80 | 08/07/2015 | Salmon | 4.30 | 01/07/2015 | Biscuits | 2.40 | 15/12/2015 | Milk | 1.00 |...

I need help setting the RecordSource of a Report within a VBA Function


vba,ms-access,access-vba
Ok, so I've been looking around here for a few days (and a few other sites) and while I have modified my code a good bit to find a solution, it still doesn't work. I have four source queries, and I'd like to set the record source of my report...

Extract All Named Ranges Into A Class


vba,excel-vba
I have a workbook with a very large amount of named ranges (well over 200). I really need a way to work quickly and easily with all of the named ranges so I can then work with / populate them using VBA. My solution up until now has been to...

Using a cell's number to insert that many rows (with that row's data)


excel,excel-vba
I have data in excel that looks like this {name} {price} {quantity} joe // 4.99 // 1 lisa // 2.99 // 3 jose // 6.99 // 1 Would it be hard to make a macro that will take the quantity value ("lisa // 3.99 // 3") and add that many...

Excel VBA Program Code by Using Randomize Timer


vba
What is wrong in below program code, why not returning correct result. Whenever i put any number in excel cell (1,1) and run the program, Numbers changed automatically, also not throwing a correct result in cell (1,2). Please Help as i learning VBA. Private Sub Sheet2_1() Dim num1 As Integer...

Activecell not in Array


vba
Having difficulty comparing my activecell against a predefined array. After importing data from another source I want to trim out the columns I don't need I've trued the array as both undefined, string and variant And tried activecell / activecell.value <> NeededColumns No joy :( Sub Trim() Dim NeededColumns As...

adding variables into another variable vba


excel,vba,excel-vba
Dim x As Long Dim y As Long Dim CDTotal As Double Dim CSTotal As Double Dim ETotal As Double Dim FTotal As Double Dim HTotal As Double Dim ITotal As Double Dim ITTotal As Double Dim MTotal As Double Dim TTotal As Double Dim UTotal As Double Dim TotalValue...

VBA - Unable to pass value from Private to Public Sub


excel,vba,excel-vba
I have a tool which I am designing to present a number of questions to a user in a set of userforms. The form will generate a score via passing an integer result from the userform to a main sub, which passes the code to a worksheet. My problem is...

Copying a Range from Excel and Pasting it into Powerpoint NOT as a metafile but as a table which you can edit in PPP


vba,excel-vba,powerpoint-vba
All I want to do is copy a range from Excel and then paste this range into PowerPoint. When my range is manually copied from Excel to the clipboard... If I right click on a blank slide when pasting into PowerPoint, it gives me the option to paste "using destination...