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
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Statement invalid outside Type block |
vblr6.chm1040053 |
vblr6.chm1040053 |
office |
287d4cf7-257a-2cc4-2e5d-42e578c8b862 |
06/08/2017 |
medium |
The syntax for declaring variables outside a Type…End Type statement block is different from the syntax for declaring the elements of the user-defined type. This error has the following causes and solutions:
- You tried to declare a variable outside a Type…End Type block or outside a statement. When declaring a variable with an As clause outside a Type…End Type block, use one of the declaration statements, Dim, ReDim, Static, Public, or Private. For example, the first declaration of
MyVar
in the following code generates this error; the second and third declarations ofMyVar
are valid:
MyVar As Double ' Invalid declaration syntax. Dim MyVar As Double Type AType MyVar As Double ' This is valid declaration syntax End Type ' because it's inside a Type block.
- You used an End Type statement without a corresponding Type statement. Check for an unmatched End Type, and either precede its block with a Type statement, or delete the End Type statement if it isn’t needed.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
|
|
hi,
I have the following code in a module:
Public Function ExportToExcel(TableName As String, FilePathname As String, _
Optional SheetName As String) As Boolean
Dim oRS As Object, oExcelApp As Object, lngFieldCounter As Long
Dim blnFileExists As Boolean, blnExcelRunning As Boolean, oTargetSheet As Object
On Error GoTo errHandler
‘Firstly, open the recordset. The TableName argument can be either a table name or
‘a valid SQL statement.
Set oRS = CreateObject(«DAO.Recordset»)
oRS.Open TableName, CurrentDb.Connection, 0, 1
‘Get an instance of Excel. Use a running instance if one exists or create one if not.
On Error Resume Next
Set oExcelApp = GetObject(, «Excel.Application»)
If Err.Number <> 0 Then
blnExcelRunning = False
Set oExcelApp = CreateObject(«Excel.Application»)
Else
blnExcelRunning = True
End If
On Error GoTo errHandler
‘Now see if the specified file exists or create it if not.
If Dir(FilePathname) <> «» Then
blnFileExists = True
oExcelApp.Workbooks.Open Filename:=FilePathname
Else
oExcelApp.Workbooks.Add
End If
‘Get a reference to the sheet we’re going to dump the data into. If it already exists
‘then use that, otherwise add a sheet and name it.
If IsEmpty(SheetName) = False Then
On Error Resume Next
Set oTargetSheet = oExcelApp.ActiveWorkbook.Sheets(SheetName)
If Err.Number <> 0 Then
Set oTargetSheet = oExcelApp.ActiveWorkbook.Sheets.Add
oTargetSheet.Name = SheetName
End If
Else
Set oTargetSheet = oExcelApp.ActiveWorkbook.Sheets.Add
End If
On Error GoTo errHandler
‘This loop will place the recordset field names into row 1 of the worksheet
For lngFieldCounter = 1 To oRS.Fields.Count
oTargetSheet.Cells(1, lngFieldCounter) = oRS.Fields(lngFieldCounter — 1).Name
Next lngFieldCounter
oTargetSheet.Range(«A2»).CopyFromRecordset oRS
oRS.Close
‘Now save the Excel workbook and clean up
If blnFileExists Then
oExcelApp.ActiveWorkbook.Save
Else
oExcelApp.ActiveWorkbook.SaveAs Filename:=FilePathname
End If
oExcelApp.ActiveWorkbook.Close
If Not blnExcelRunning Then
oExcelApp.Quit
Set oExcelApp = Nothing
End If
Set oRS = Nothing
ExportToExcel = True
Exit Function
errHandler:
ExportToExcel = False
End Function
————
I use the following to call the function:
Sub ExportCMStatsToExcelSheet_Click()
ExportToExcel(«tblCMCode», «C:CMCodeStats.xls», «CMCodeStats») As Boolean
End Sub
When I compile it, I am getting a «Statement Invalid Outside Type Block».
Does anyone know how to fix this? Please?
Thank you in advance…
6
I am trying to run a module from a button on a form where I populate a subform from Query1 with a product formula. The module is supposed to check whether the product formula can be implemented given enough raw material inventory. So, I’m trying to loop through my product formula based on OrderID and MaterialID(Material Name) and check against the current stock inventory table. If any of the ingredients required for the product to be made is over the available stock inventory on hand, then I want an error to be displayed, otherwise I don’t want any errors.
The problem I’m having is with the Compile Error at the line where it states:
- Sub check_quantity ()
I’d appreciate any help possible, THANKS!!
The entire code is as follows:
- Option Compare Database
- Option Explicit
- Sub check_quantity()
- On Error GoTo err_check_quantity
- Dim material As Variant
- Dim totalKg As Variant
- queryString As String
- queryString2 As String
- Quantity As Variant
- valid As Integer
- strMsg As String
- Dim Rs As DAO.Recordset
- Dim Rs2 As DAO.Recordset
- Dim Db As DAO.Database
- Set Db = CurrentDb()
- queryString = «SELECT * FROM Query1 WHERE [ProductName] = ‘» & [Forms]![Batchsheet Subform]![ProductName] & «‘ AND [OrderID] = » & [Forms]![Batchsheet Subform]![OrderID] & «;»
- Set Rs = Db.OpenRecordset(queryString, dbOpenDynaset)
- If Not (Rs.BOF And Rs.EOF) Then
- Rs.MoveLast
- Rs.MoveFirst
- With Rs
- Do While Not Rs.EOF
- material = Rs.Fields(«MaterialID»).Value
- totalKg = Rs.Fields(«Total (kg)»).Value
- queryString2 = «SELECT * FROM RawMaterials WHERE [ItemName] = ‘» & material & «;»
- Set Rs2 = Db.OpenRecordset(queryString2, dbOpenDynaset)
- If Not (Rs2.BOF And Rs2.EOF) Then
- Rs2.MoveLast
- Rs2.MoveFirst
- Quantity = Rs2.Fields(«InStock»).Value
- If totalKg > Quantity Then
- valid = 0
- Else
- valid = 1
- End If
- Select Case valid
- Case 0
- strMsg = » Order cannot currently be completed» & _
- vbCrLf & » Please verify you have enough » & material & «inventory to complete this order.»
- MsgBox strMsg, vbInformation, «INVALID Raw Material Level»
- Case 1
- Rs.MoveNext
- End Select
- Loop
- End With
- Rs.Close
- Rs2.Close
- Db.Close
- Set Rs = Nothing
- Set Rs2 = Nothing
- Set Db = Nothing
- exit_check_quantity:
- Exit Sub
- err_check_quantity:
- MsgBox Err.decsription
- Resume exit_check_quantity
- End Sub
Jul 21 ’10
#1
NeoPa: Your Do…Loops, and If…End Ifs, and With…End Withs do not balance up correctly.
You need to get these sorted before continuing, and certainly before it will work.
Welcome to Bytes!
I would add :
- Line #75 closes CurrentDB. Not a good idea. If your code opens an object then it should close it. If it finds it already open, then it should leave it open. There may be exceptions to this rule, but they’re rare.
- Line #81 is probably the offending property. You want Err.Description.
Remember next time to include the line number though please.
-
#1
I’m getting the error in the title of the thread and VBA highlights the time_lastcell2 as the culprit.
Code:
Dim first_cell As Integer
Dim time2 As Worksheet
Set time2 = ActiveWorkbook.Sheets("time")
Dim lastday As Date, lastday_time As Date
time_lastcell2 As Integer
With time2
time_lastcell2 = .Range("e65000").End(xlUp).Row
End With
lastday_time = time2.Range("e" & time_lastcell).Address
'Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
With ActiveSheet
first_cell = .Range("c65000").End(xlUp).Row
lastday = .Range("b" & first_cell).Address
[more code]
Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
-
#2
kylefoley76,
Missing Dim….
Dim time_lastcell2 As Integer
-
#3
Missing Dim….
Dim time_lastcell2 As Integer
Also, since it will hold a row number, I would suggest declaring it as a Long instead of as an Integer…
Dim time_lastcell2 As Long
-
#4
Thanks that did it. Also Rick, about the fact that I thought you didn’t like one-liners expressing gratitude. I thought I read that on excelfox but I went back to look for it and I couldn’t find it.
Brent
-
#1
I have a cell that I want to display a message box for. The cell
should not contain more than 28 characters. If it does I want to
display a message box that tells the user how many characters they
entered and how many characters to remove from their entry. This is
my code.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cce17 As Double
If Not Application.Intersect(Target, Range(«E17»)) Is Nothing Then
cce17 = Len(E17)
If cce17 > 28 Then
MsgBox(«You have entered a value in this field that is» &
cce17 & » characters in length. You will need to shorten your entry
by » & 28 — cce17 & «characters.», vbAbortRetryIgnore, «InvalidEntry
«) As VbMsgBoxResult
End If
End If
End Sub
When I try to compile the code I get an error that says
Compile error:
Statement invalid outside Type block.
I know this is probably simple but I am a beginner to VBA and have
been unable to figure it out.
Thanks,
Brent Blevins
Advertisements
Chip Pearson
-
#2
Brent,
Get rid of the «As VbMsgBoxResult» in your MsgBox line of code,
and remove the parentheses from that line.
—
Cordially,
Chip Pearson
Microsoft MVP — Excel
Pearson Software Consulting, LLC
www.cpearson.com
rcuatman
-
#3
I made the changes you suggest. Now moy code looks like this:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cce17 As Double
If Not Application.Intersect(Target, Range(«E17»)) Is Nothing Then
cce17 = Len(E17)
If cce17 > 28 Then
MsgBox(You have entered a value in this field that is &
cce17 & characters in length. You will need to shorten your entry by
& 28 — cce17 & characters., vbAbortRetryIgnore, «InvalidEntry «)
End If
End If
End Sub
And it will not compile. I get a syntax error.
Did I miss something?
Dave Peterson
-
#4
» = quotes
() = parentheses
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim cce17 As Double
If Not Application.Intersect(Target, Range(«E17»)) Is Nothing Then
cce17 = Len(Target.Value)
If cce17 > 28 Then
MsgBox «You have entered a value in this field that is » _
& cce17 & » characters in length. » _
& «You will need to shorten your entry by » & cce17 — 28 _
& » characters.», vbAbortRetryIgnore, «InvalidEntry»
End If
End If
End Sub
But I would think that this would be under the worksheet_change event—don’t
check when the user changes the selection, check when they hit the enter key.
Advertisements
-
#5
I have had very similar issues. It turns out that the newer version of Excel doesn’t allow multi-code parsing. Thanks for the pointers Rick, it provided me a starting point to research this issue.
-C.W.
Excel Statement
Want to reply to this thread or ask your own question?
You’ll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.
Ask a Question
У меня есть приведенный ниже код, который объединяет/объединяет все повторяющиеся строки с одним и тем же текстом в столбцах 1-4 и суммирует значение в столбце 5.
Код работал правильно в течение некоторого времени, но внезапно перестал работать, и я столкнулся с приведенным ниже сообщением об ошибке:
Ошибка компиляции:
Statement invalid outside type block
Любая помощь в решении этого вопроса будет высоко оценена
Sub nSum()
Dim Rng As Range, Dn As Range, n As Long, Txt As String, Ac As Long
Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
ray(1 To Rng.Count, 1 To 4) 'Column count ''***ERROR LINE***************
With CreateObject("scripting.dictionary")
.CompareMode = vbTextCompare
For Each Dn In Rng
Txt = Join(Application.Transpose(Application.Transpose(Dn.Resize(, 3))), ",")
If Not .Exists(Txt) Then
n = n + 1
For Ac = 1 To 4: ray(n, Ac) = Dn.Offset(, Ac - 1): Next Ac
.Add Txt, n
Else
ray(.Item(Txt), 4) = ray(.Item(Txt), 4) + Dn.Offset(, 3)
End If
Next
n = .Count
End With
With Sheets("Sheet2").Range("A1").Resize(n, 4)
.Value = ray
.Borders.Weight = 2
.Columns.AutoFit
End With
End Sub'