Compile error statement invalid outside type block

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

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 of MyVar 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]

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Statement Invalid outside TypeBlock error

  1. Dec 20th, 2005, 05:27 PM


    #1

    VTuser is offline

    Thread Starter


    New Member


    Question Statement Invalid outside TypeBlock error

    I am getting the following error

    Compile error
    Statement Invalid outside TypeBlock

    «Function DecimalTime» is highlighted in yellow

    what does it mean?? and thoughts on how to fix it??

    code below

    Private Sub cmdIn_Click()
    TimeIn = DecimalTime
    AddToDB
    End Sub

    Function DecimalTime()

    ClockTime As Date

    If Minute(Time) >= 0 And Minute(Time) <= 7 Then
    ClockTime = DateAdd(«n», -Minute(Time), Time)
    ElseIf Minute(Time) >= 8 And Minute(Time) <= 22 Then
    ClockTime = DateAdd(«n», 15 — Minute(Time), Time)
    ElseIf Minute(Time) >= 23 And Minute(Time) <= 37 Then
    ClockTime = DateAdd(«n», 30 — Minute(Time), Time)
    ElseIf Minute(Time) >= 38 And Minute(Time) <= 52 Then
    ClockTime = DateAdd(«n», 45 — Minute(Time), Time)
    Else
    ClockTime = DateAdd(«n», 60 — Minute(Time), Time)
    End If

    DecimalTime = Format(ClockTime * 24, «0.00»)

    End Function


  2. Dec 20th, 2005, 05:36 PM


    #2

    Re: Statement Invalid outside TypeBlock error

    Shouldn’t your function be declared to return something????


  3. Dec 20th, 2005, 05:40 PM


    #3

    Re: Statement Invalid outside TypeBlock error

    Functions return Variants by default so that’s not the problem, but where do you have the function coded? Is there a Type block above it that doesn’t have an End Type?


  4. Dec 20th, 2005, 05:45 PM


    #4

    Re: Statement Invalid outside TypeBlock error

    Just change ‘ClockTime As Date’ to ‘Dim ClockTime As Date’.

    Ash Nazg durbatuluk, Ash Nazg gimbatul, Ash Nazg tharkathuluk, Agh barzum-ishi krimpatul.


  5. Dec 20th, 2005, 05:46 PM


    #5

    Re: Statement Invalid outside TypeBlock error

    ‘Dim’ is required for declaring variables whenever it’s outside a «Type» block.

    Ash Nazg durbatuluk, Ash Nazg gimbatul, Ash Nazg tharkathuluk, Agh barzum-ishi krimpatul.


  6. Dec 20th, 2005, 05:48 PM


    #6

    Re: Statement Invalid outside TypeBlock error

    Quote Originally Posted by Frodo_Baggins

    Just change ‘ClockTime As Date’ to ‘Dim ClockTime As Date’.

    Of course! I missed that because he said that the function header was the problem.


  7. Dec 20th, 2005, 06:57 PM


    #7

    VTuser is offline

    Thread Starter


    New Member


    Re: Statement Invalid outside TypeBlock error

    since I am dealing with the same app I have two more issues

    I am entering the system time, which I am converting to decimal into an access 2003 database field called IN that has data type date/time

    two issues

    1. the system time is 6:37PM the time that’s entered into the access database is 6:51PM

    as you can notice I am rounding up or down depending on the minutes in 15 minute intervals.
    Thus why am I getting that extra minute added. I think it has to do with the access database but not sure
    any ideas????

    2. How can I change in access to the field does not read 6:51PM but 6.50 (decimal format))

    any ideas

    Private Sub cmdIn_Click()
    TimeIn = DecimalTime
    AddToDB
    End Sub

    Function DecimalTime()

    Dim ClockTime As Date

    If Minute(Time) >= 0 And Minute(Time) <= 7 Then
    ClockTime = DateAdd(«n», -Minute(Time), Time)

    ElseIf Minute(Time) >= 8 And Minute(Time) <= 22 Then
    ClockTime = DateAdd(«n», 15 — Minute(Time), Time)

    ElseIf Minute(Time) >= 23 And Minute(Time) <= 37 Then
    ClockTime = DateAdd(«n», 30 — Minute(Time), Time)

    ElseIf Minute(Time) >= 38 And Minute(Time) <= 52 Then
    ClockTime = DateAdd(«n», 45 — Minute(Time), Time)

    Else
    ClockTime = DateAdd(«n», 60 — Minute(Time), Time)
    End If

    DecimalTime = Format(ClockTime * 24, «0.00»)

    Private Sub AddToDB()
    rs.AddNew
    rs.Fields(«IN») = TimeIn
    rs.Fields(«Site») = cboSites.Text
    rs.Fields(«Activity») = cboActivity.Text
    rs.Update
    End Sub


  8. Dec 20th, 2005, 07:00 PM


    #8

    Re: Statement Invalid outside TypeBlock error

    Please use vbcode tags in your post for your code. It makes it more readable.


  9. Dec 20th, 2005, 07:05 PM


    #9

    Re: Statement Invalid outside TypeBlock error

    BTW: Don’t understand what you are doing. 6:37 + 15 = 6:52… Better example please…


  10. Dec 21st, 2005, 11:04 AM


    #10

    VTuser is offline

    Thread Starter


    New Member


    Re: Statement Invalid outside TypeBlock error

    Example

    The system time is 6:37PM

    The click event for cmdIn

    Calls the decimaltime function

    The decimaltime function using if elseif statements determine the statement is applied based on the minutes of the system time. In this case 6:37PM has 37 minutes thus

    ElseIf Minute(Time) >= 23 And Minute(Time) <= 37 Then
    ClockTime = DateAdd(«n», 30 — Minute(Time), Time)

    Is applied and it convert 37 minutes to 30 minutes and the system time know is 6:30PM
    The reason for this is that I want to capture time in 15 intervals only

    From there

    DecimalTime = Format(ClockTime * 24, «0.00»)

    Takes 6:30PM and converts it to decimal format which is 6.50 then that value is placed in the variable TimeIn

    Then it�s added to the database using the following procedure

    VB Code:

    1. Private Sub AddToDB()

    2. rs.AddNew

    3. rs.Fields("IN") = TimeIn

    4. rs.Fields("Site") = cboSites.Text

    5. rs.Fields("Activity") = cboActivity.Text

    6. rs.Update

    7. End Sub

    I hope this clears things up and that you have an idea how to solve my issues. Thanks

    VB Code:

    1. Private Sub cmdIn_Click()

    2. TimeIn = DecimalTime

    3. AddToDB

    4. End Sub

    5. Function DecimalTime()

    6. Dim ClockTime As Date

    7. If Minute(Time) >= 0 And Minute(Time) <= 7 Then

    8. ClockTime = DateAdd("n", -Minute(Time), Time)

    9. ElseIf Minute(Time) >= 8 And Minute(Time) <= 22 Then

    10. ClockTime = DateAdd("n", 15 - Minute(Time), Time)

    11. ElseIf Minute(Time) >= 23 And Minute(Time) <= 37 Then

    12. ClockTime = DateAdd("n", 30 - Minute(Time), Time)

    13. ElseIf Minute(Time) >= 38 And Minute(Time) <= 52 Then

    14. ClockTime = DateAdd("n", 45 - Minute(Time), Time)

    15. Else

    16. ClockTime = DateAdd("n", 60 - Minute(Time), Time)

    17. End If

    18. DecimalTime = Format(ClockTime * 24, "0.00")

    19. Private Sub AddToDB()

    20. rs.AddNew

    21. rs.Fields("IN") = TimeIn

    22. rs.Fields("Site") = cboSites.Text

    23. rs.Fields("Activity") = cboActivity.Text

    24. rs.Update

    25. End Sub

    Edit: Fixed [vbcode][/vbcode] tags. — Hack

    Last edited by Hack; Dec 21st, 2005 at 11:07 AM.


  11. Dec 21st, 2005, 11:36 AM


    #11

    Re: Statement Invalid outside TypeBlock error

    You don’t want to do a dateadd when checking. All you want to do is take the Hour then concatenate the decimal minutes you figured out to that. You are over complicating the whole process.


  12. Dec 21st, 2005, 11:43 AM


    #12

    VTuser is offline

    Thread Starter


    New Member


    Re: Statement Invalid outside TypeBlock error

    can you if me an example

    thanks


  13. Dec 21st, 2005, 11:55 AM


    #13

    Re: Statement Invalid outside TypeBlock error

    Here’s an example:

    VB Code:

    1. Dim mTime As Time

    2. mTime = Time

    3. Select Case mTime

    4.     Case >= 8 and <= 22

    5.         decHours = decHours & ".15"

    6.     Case >= 22 and <= 37

    7.         decHours = decHours & ".30"

    8. End Select


  14. Dec 21st, 2005, 11:57 AM


    #14

    Re: Statement Invalid outside TypeBlock error

    Quote Originally Posted by randem

    Here’s an example:

    VB Code:

    1. Dim mTime As Time

    2. mTime = Time

    3. Select Case mTime

    4.     Case >= 8 and <= 22

    5.         decHours = decHours & ".15"

    6.     Case > 22 and <= 37

    7.         decHours = decHours & ".30"

    8. End Select

    Select Case isn’t going to like this. You would need to do something like

    VB Code:

    1. Case 8 To 22

    2. Case 23 To 37


  15. Dec 21st, 2005, 12:15 PM


    #15

    Re: Statement Invalid outside TypeBlock error


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Statement Invalid outside TypeBlock error


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

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:

  1.  Sub check_quantity () 

I’d appreciate any help possible, THANKS!!

The entire code is as follows:

  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Sub check_quantity()
  5. On Error GoTo err_check_quantity
  6.  
  7. Dim material As Variant
  8. Dim totalKg As Variant
  9. queryString As String
  10. queryString2 As String
  11. Quantity As Variant
  12. valid As Integer
  13. strMsg As String
  14. Dim Rs As DAO.Recordset
  15. Dim Rs2 As DAO.Recordset
  16. Dim Db As DAO.Database
  17.  
  18.  
  19. Set Db = CurrentDb()
  20.  
  21. queryString = «SELECT * FROM Query1 WHERE [ProductName] = ‘» & [Forms]![Batchsheet Subform]![ProductName] & «‘ AND [OrderID] = » & [Forms]![Batchsheet Subform]![OrderID] & «;»
  22.  
  23. Set Rs = Db.OpenRecordset(queryString, dbOpenDynaset)
  24.  
  25. If Not (Rs.BOF And Rs.EOF) Then
  26. Rs.MoveLast
  27. Rs.MoveFirst
  28.  
  29. With Rs
  30. Do While Not Rs.EOF
  31.  
  32. material = Rs.Fields(«MaterialID»).Value
  33. totalKg = Rs.Fields(«Total (kg)»).Value
  34.  
  35. queryString2 = «SELECT * FROM RawMaterials WHERE [ItemName] = ‘» & material & «;»
  36.  
  37. Set Rs2 = Db.OpenRecordset(queryString2, dbOpenDynaset)
  38.  
  39. If Not (Rs2.BOF And Rs2.EOF) Then
  40. Rs2.MoveLast
  41. Rs2.MoveFirst
  42.  
  43.  
  44.   Quantity = Rs2.Fields(«InStock»).Value
  45.  
  46.  
  47.      If totalKg > Quantity Then
  48.         valid = 0
  49.      Else
  50.         valid = 1
  51.      End If
  52.  
  53.      Select Case valid
  54.  
  55.      Case 0
  56.             strMsg = » Order cannot currently be completed» & _
  57.                         vbCrLf & » Please verify you have enough » & material & «inventory to complete this order.»
  58.             MsgBox strMsg, vbInformation, «INVALID Raw Material Level»
  59.  
  60.      Case 1
  61.             Rs.MoveNext
  62.  
  63.      End Select
  64.  
  65. Loop
  66. End With
  67.  
  68.  
  69.    Rs.Close
  70.    Rs2.Close
  71.    Db.Close
  72.  
  73.    Set Rs = Nothing
  74.    Set Rs2 = Nothing
  75.    Set Db = Nothing
  76.  
  77. exit_check_quantity:
  78.     Exit Sub
  79.  
  80. err_check_quantity:
  81.     MsgBox Err.decsription
  82.     Resume exit_check_quantity
  83.  
  84. End Sub
  85.  
  86.  

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 :

  1. 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.
  2. 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?:confused:

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'

Понравилась статья? Поделить с друзьями:
  • Compile error object required vba
  • Compile error next without for
  • Compile error method or data member not found vba
  • Compile error macro excel
  • Compile error invalid use of property