Invalid outside procedure vba excel

For the life of me I cannot figure out why the following code is throwing a compile error with the message «Invalid outside procedure». It is highlighting the error on the starred line below.

Option Explicit

Dim shtThisSheet As Worksheets

**Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")**

Sub Formatting()

    With shtThisSheet

        With Range("A1")
            .Font.Bold = True
            .Font.Size = 14
            .HorizontalAlignment = xlLeft
        End With

        With Range("A3:A6")
            .Font.Bold = True
            .Font.Italic = True
            .Font.ColorIndex = 5
            .InsertIndent 1
        End With

        With Range("B2:D2")
            .Font.Bold = True
            .Font.Italic = True
            .Font.ColorIndex = 5
            .HorizontalAlignment = xlRight
        End With

        With Range("B3:D6")
            .Font.ColorIndex = 3
            .NumberFormat = "$#,##0"
        End With

    End With

End Sub

Michael Liu's user avatar

Michael Liu

51.1k13 gold badges117 silver badges149 bronze badges

asked Feb 10, 2016 at 15:31

Zack Withrow's user avatar

2

Set statements aren’t allowed outside procedures. Move the Set statement into the Formatting procedure:

Sub Formatting()
    Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")
    ...

(I’d move the Dim statement into the procedure as well. I prefer to avoid global variables when possible.)

answered Feb 10, 2016 at 15:33

Michael Liu's user avatar

Michael LiuMichael Liu

51.1k13 gold badges117 silver badges149 bronze badges

3

You can declare variables as global, but you cannot set them outside of a procedure such as a sub or function.

If you need this variable as a global, then it’s best to set it on.
Workbook_Open()

If you do not need it as a global, then move both the declaration and the set statement into your procedure

answered Feb 10, 2016 at 18:36

invalid outside procedure

Blin

Дата: Понедельник, 04.05.2015, 04:32 |
Сообщение № 1

Группа: Пользователи

Ранг: Прохожий

Сообщений: 8


Репутация:

0

±

Замечаний:
20% ±


Excel 2013

Хай.
Есть ексель книга, в ней 3 листа. пишу в ней vba скрипт

[vba]

Код

dim foo
dim bar
dim foo1
set foo = worksheets(«Лист1»)
dim …
dim …
sub cool_sub()
используем ранее объявленные переменные foo И bar
end sub
sub second_cool_sub()
используем ранее объявленные переменные foo И bar
end sub

[/vba]
смысл в том, что я хочу вначале один раз объявить некие переменные с именем листов, диапазонов. а далее во всех субах на них ссылаться.
При выполнении какой либо субы вылетает ошибка. Так нельзя?

 

Ответить

Pelena

Дата: Понедельник, 04.05.2015, 09:19 |
Сообщение № 2

Группа: Админы

Ранг: Местный житель

Сообщений: 18797


Репутация:

4284

±

Замечаний:
±


Excel 2016 & Mac Excel

Blin, есть такая примета: если автор вопроса не отписывается в своих темах, подошло решение или нет, то у отвечающих пропадает желание помогать такому автору, потому что нет смысла отвечать в пустоту


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

AndreTM

Дата: Понедельник, 04.05.2015, 10:02 |
Сообщение № 3

Группа: Друзья

Ранг: Старожил

Сообщений: 1762


Репутация:

498

±

Замечаний:
0% ±


2003 & 2010

Присвоение начальных значений переменным выполняется внутри процедур, вне процедуры вы можете только определять константы.
Естественно, вы можете организовать одну процедуру «инициализации» и вызывать её один раз в нужный момент, до исполнения всего основного кода.

Определение переменной через Dim вне кода процедуры даст вам переменную с областью видимости в пределах данного модуля. Если вам нужны «глобальные» переменные, которые будут иметь областью видимости всю книгу — используйте определение через Public, а не через Dim. Определять такие переменные надо только в общих модулях книги.

Для примера:
[vba]

Код

‘ поместите код в любой общий модуль
Public goFoo As Worksheet
Public gcName As String
Dim lcName As String

Sub initVars()
     gcName = «TEST»
     lcName = «test»
     Set goFoo = ThisWorkbook.Worksheets(«Лист1»)
End Sub

‘ процедуру можно поместить в несколько разных модулей, и проверять, запуская её два раза подряд
Sub test()
     If goFoo Is Nothing Then
         MsgBox «0. ‘Foo’ is nothing»
         initVars
     Else
         MsgBox «1. ‘Foo’ is ‘» & goFoo.name & «‘» & vbCrLf & _
             «‘NAME’ is ‘» & gcName & «‘» & vbCrLf & _
             «‘name’ is ‘» & lcName & «‘»
         Set goFoo = Nothing
     End If
End Sub

[/vba]


Skype: andre.tm.007
Donate: Qiwi: 9517375010

Сообщение отредактировал AndreTMПонедельник, 04.05.2015, 10:37

 

Ответить

Blin

Дата: Понедельник, 04.05.2015, 17:17 |
Сообщение № 4

Группа: Пользователи

Ранг: Прохожий

Сообщений: 8


Репутация:

0

±

Замечаний:
20% ±


Excel 2013

‘ процедуру можно поместить в несколько разных модулей, и проверять, запуская её два раза подряд

Достаточно просто вызвать процедуру в начале каждого модуля, или надо обязательно проверять, чтоб не вызвать второй раз?

 

Ответить

AndreTM

Дата: Понедельник, 04.05.2015, 20:04 |
Сообщение № 5

Группа: Друзья

Ранг: Старожил

Сообщений: 1762


Репутация:

498

±

Замечаний:
0% ±


2003 & 2010

Достаточно просто вызвать процедуру в начале каждого модуля, или надо обязательно проверять…

Это ПРИМЕР :)
Вы вообще поняли, о чём речь шла? О том, что переменные, определенные внутри модуля, но вне процедур — должны быть проинициализированы до их использования, отдельной процедурой. И о том, что если вы собираетесь использовать переменные, определенные в каком-то модуле, вне этого модуля — то эти переменные должны быть публичными.
Саму методику как первоначальной инициализации, повторной реинициализации, а также освобождения памяти, плюс стратегию использования переменных — вы должны разрабатывать сами, исходя из решаемых вами задач…


Skype: andre.tm.007
Donate: Qiwi: 9517375010

 

Ответить

Blin

Дата: Вторник, 05.05.2015, 17:57 |
Сообщение № 6

Группа: Пользователи

Ранг: Прохожий

Сообщений: 8


Репутация:

0

±

Замечаний:
20% ±


Excel 2013

дада, понял
[vba]

Код

Public goFoo As Worksheet

Public gcName As String

Dim lcName As String

Sub initVars()

gcName = «TEST»

lcName = «test»

Set goFoo = ThisWorkbook.Worksheets(«Лист1»)

End Sub

Sub test()

initVars

do some things…

End Sub

[/vba]

Сообщение отредактировал BlinВторник, 05.05.2015, 17:59

 

Ответить

  • Remove From My Forums
  • Question

  • Hello all,

    I am trying to convert a string to UTF-8 in VBA-Excel, my final aim is to do URL-encoding to UTF-8.

    After a lot of searches I found this code that can help me to implement, it uses the Encoding Class:
    http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx 

    It starts with:

    Imports System
    Imports System.Text
    Imports Microsoft.VisualBasic

    But when I put the code example in the excel-VBA editor I get an error «Invalid outside procedure».

    Please help, what sould I do?

    p.s: if anyone has an example that can implement all the URL encoding to UTF-8 I will be grathfull to.

Answers

  • This is VB.NET code and the classes/methods you want to use cannot be used in VBA directly.  What you can do is to look for a replacement which can be used in VBA directly or to create a VB.NET DLL, expose the desired functionality to COM and then
    reference the .NET assembly (or more specifically, the TLB) from VBA.  However, I’d recomment to take the first of the two ways I described.


    Herfried K. Wagner [MVP]

    • Marked as answer by

      Saturday, June 26, 2010 2:48 PM

  • If you want to ask your question in the VBA forum you can find it here

     http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/c147bae1-c9db-4ae8-9557-43713004cc94


    Coding4fun Be a good forum member mark posts that contain the answers to your questions or those that are helpful

    Please format the code in your posts with the button . Makes it easier to read . Or use the Forum Code Formatter by JohnWein http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/bf977a14-d9d4-4e84-9784-bf76b9e23261

    • Marked as answer by
      Liliane Teng
      Saturday, June 26, 2010 2:48 PM

  • Hello elAlladin,
    Thanks for your post.
    VBA stands for Visual Basic for Applications which is available in Excel, and other office applications.
    About VB.net, one can create a stand-alone windows application, which is not possible with VBA.
    Check the following link about their detailed difference. Hope it helpful.
    http://allfaq.org/forums/t/178686.aspx
    http://answers.google.com/answers/threadview/id/217809.html

    This forum is for VB.NET questions only (e.g. Visual Basic 2003, Visual Basic 2005, Visual Basic 2008).
    For VBA questions,you could post it on VBA forums as bdbodger suggested for better and  quicker support.

    Best regards,
    Liliane


    Please mark the replies as answers if they help and unmark them if they provide no help. Thanks

    • Marked as answer by
      Liliane Teng
      Saturday, June 26, 2010 2:48 PM

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Invalid outside procedure

vblr6.chm1040051

vblr6.chm1040051

office

46c00b2b-c656-9ad4-bff9-d341a6a7ecd5

06/08/2017

medium

The statement must occur within a Sub or Function, or a property procedure (Property Get, Property Let, Property Set). This error has the following cause and solution:

  • An executable statement, Static or ReDim, appears at module level.

    Static is unnecessary at module level, since all module-level variables are static. Use Dim instead of ReDim at module level. To create a dynamic array at module level, declare it with Dim using empty parentheses.

    Note At module level, you can use only comments and declarative statements, such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type. The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

[!includeSupport and feedback]

Содержание

  1. Invalid outside procedure
  2. Support and feedback
  3. Name already in use
  4. VBA-Docs / Language / Reference / User-Interface-Help / invalid-outside-procedure.md
  5. Compile Error: Invalid Outside Procedure
  6. Compile Error: Invalid Outside Procedure
  7. Re: Compile Error: Invalid Outside Procedure
  8. Re: Compile Error: Invalid Outside Procedure
  9. Re: Compile Error: Invalid Outside Procedure
  10. Re: Compile Error: Invalid Outside Procedure
  11. Re: Compile Error: Invalid Outside Procedure
  12. Re: Compile Error: Invalid Outside Procedure
  13. Re: Compile Error: Invalid Outside Procedure
  14. Compile Error: Invalid Outside Procedure
  15. Compile Error: Invalid Outside Procedure
  16. Re: Compile Error: Invalid Outside Procedure
  17. Re: Compile Error: Invalid Outside Procedure
  18. Re: Compile Error: Invalid Outside Procedure
  19. Re: Compile Error: Invalid Outside Procedure
  20. Re: Compile Error: Invalid Outside Procedure
  21. Re: Compile Error: Invalid Outside Procedure
  22. Re: Compile Error: Invalid Outside Procedure
  23. MACRO Error — ‘Invalid outside procedure’
  24. MACRO Error — ‘Invalid outside procedure’
  25. Re: MACRO Error — ‘Invalid outside procedure’

Invalid outside procedure

The statement must occur within a Sub or Function, or a property procedure (Property Get, Property Let, Property Set). This error has the following cause and solution:

An executable statement, Static or ReDim, appears at module level.

Static is unnecessary at module level, since all module-level variables are static. Use Dim instead of ReDim at module level. To create a dynamic array at module level, declare it with Dim using empty parentheses.

Note At module level, you can use only comments and declarative statements, such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type. The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Name already in use

VBA-Docs / Language / Reference / User-Interface-Help / invalid-outside-procedure.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

Invalid outside procedure

The statement must occur within a Sub or Function, or a property procedure (Property Get, Property Let, Property Set). This error has the following cause and solution:

An executable statement, Static or ReDim, appears at module level.

Static is unnecessary at module level, since all module-level variables are static. Use Dim instead of ReDim at module level. To create a dynamic array at module level, declare it with Dim using empty parentheses.

Note At module level, you can use only comments and declarative statements, such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type. The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

Источник

Compile Error: Invalid Outside Procedure

LinkBack
Thread Tools
Rate This Thread
Display

Compile Error: Invalid Outside Procedure

Hello, I hope that someone can help with the following problem.

I have created an Excel file on my desktop (in Excel 2007) that contains some basic macro commands. This file is saved to my Dropbox cloud folder.

I also have the same Dropbox cloud folder installed on my laptop.

When I open the same Excel file on my laptop (running Excel 2010) I get a Microsoft Visual Basic screen (that relates to one of the Macros) pop up and the message, ‘Compile Error: Invalid Outside Procedure’.

I can close the Microsoft Visual Basic screen pop ups and carry on editing the file, but each time a make a change the same thing happens again, and I cannot run the macros.

Any help on resolving this irritating issue would be much appreciated.

Re: Compile Error: Invalid Outside Procedure

The code module starts with Private Sub. () and ends with End sub. Check if you have any lines of data outside these 2.

Press Alt+F11 and it will bring up the code.

Re: Compile Error: Invalid Outside Procedure

Thank you for replying. I will try that. I am not very technical with Excel or computing, so please bear with me if I get it wrong. Do I press Alt+F11 when I am seeing the Visual Basic pop-ups?

Re: Compile Error: Invalid Outside Procedure

Close the popup or click on OK button if present. Then while looking at your excel file, press Alt+F11.

Re: Compile Error: Invalid Outside Procedure

ALT+F11 does not bring up anything on my laptop (it just allows me to adjust the speaker volume). Anyway, the visual basic pop-up looks like it is the code, and while I can see ‘End Sub’ when I scroll to the bottom of the code page, I cannot see ‘Private Sub’ anywhere on the page.

The page starts as follows:


‘ Pricecomma Macro
‘ Inserts commas in the price to pay

‘ Keyboard shortcut: Ctrl+p

After that, there is all the specific macro code, and right at the bottom of that is, ‘End Sub’.

Re: Compile Error: Invalid Outside Procedure

put Private Sub Test() You can replace Test with anything.

Re: Compile Error: Invalid Outside Procedure

That seems to have sorted it! Thank you very much.

Re: Compile Error: Invalid Outside Procedure

Based on your last post in this thread, its apparent that you are satisfied with the solution(s) you’ve received and have solved your question, but you haven’t marked your thread as «SOLVED». I will do it for you this time.

In future, to mark your thread as Solved, you can do the following —
Select Thread Tools-> Mark thread as Solved.

Incase your issue is not solved, you can undo it as follows —
Select Thread Tools-> Mark thread as Unsolved.

Also, since you are relatively new to the forum, i would like to inform you that you can thank those who have helped you by clicking the small star icon located in the lower left corner of the post which helped you. This adds to the reputation of the person who has taken the time to help you.

Источник

Compile Error: Invalid Outside Procedure

LinkBack
Thread Tools
Rate This Thread
Display

Compile Error: Invalid Outside Procedure

Hello, I hope that someone can help with the following problem.

I have created an Excel file on my desktop (in Excel 2007) that contains some basic macro commands. This file is saved to my Dropbox cloud folder.

I also have the same Dropbox cloud folder installed on my laptop.

When I open the same Excel file on my laptop (running Excel 2010) I get a Microsoft Visual Basic screen (that relates to one of the Macros) pop up and the message, ‘Compile Error: Invalid Outside Procedure’.

I can close the Microsoft Visual Basic screen pop ups and carry on editing the file, but each time a make a change the same thing happens again, and I cannot run the macros.

Any help on resolving this irritating issue would be much appreciated.

Re: Compile Error: Invalid Outside Procedure

The code module starts with Private Sub. () and ends with End sub. Check if you have any lines of data outside these 2.

Press Alt+F11 and it will bring up the code.

Re: Compile Error: Invalid Outside Procedure

Thank you for replying. I will try that. I am not very technical with Excel or computing, so please bear with me if I get it wrong. Do I press Alt+F11 when I am seeing the Visual Basic pop-ups?

Re: Compile Error: Invalid Outside Procedure

Close the popup or click on OK button if present. Then while looking at your excel file, press Alt+F11.

Re: Compile Error: Invalid Outside Procedure

ALT+F11 does not bring up anything on my laptop (it just allows me to adjust the speaker volume). Anyway, the visual basic pop-up looks like it is the code, and while I can see ‘End Sub’ when I scroll to the bottom of the code page, I cannot see ‘Private Sub’ anywhere on the page.

The page starts as follows:


‘ Pricecomma Macro
‘ Inserts commas in the price to pay

‘ Keyboard shortcut: Ctrl+p

After that, there is all the specific macro code, and right at the bottom of that is, ‘End Sub’.

Re: Compile Error: Invalid Outside Procedure

put Private Sub Test() You can replace Test with anything.

Re: Compile Error: Invalid Outside Procedure

That seems to have sorted it! Thank you very much.

Re: Compile Error: Invalid Outside Procedure

Based on your last post in this thread, its apparent that you are satisfied with the solution(s) you’ve received and have solved your question, but you haven’t marked your thread as «SOLVED». I will do it for you this time.

In future, to mark your thread as Solved, you can do the following —
Select Thread Tools-> Mark thread as Solved.

Incase your issue is not solved, you can undo it as follows —
Select Thread Tools-> Mark thread as Unsolved.

Also, since you are relatively new to the forum, i would like to inform you that you can thank those who have helped you by clicking the small star icon located in the lower left corner of the post which helped you. This adds to the reputation of the person who has taken the time to help you.

Источник

MACRO Error — ‘Invalid outside procedure’

LinkBack
Thread Tools
Rate This Thread
Display

MACRO Error — ‘Invalid outside procedure’

I need to use the below macro but get the error ‘Compile Error: invalid outside procedure’ when i try to run.

Any help would be appreciated as i don’t know anything about Macro’s really!

Last edited by acl1992; 04-07-2017 at 07:05 AM .

Re: MACRO Error — ‘Invalid outside procedure’

Hi and welcome to the forum. Unfortunately your post does not comply with Rule 3 of our Forum RULES . Use code tags around code.

Posting code between [CODE]Please [url=https://www.excelforum.com/login.php]Login or Register [/url] to view this content.[/CODE] tags makes your code much easier to read and copy for testing, it also maintains VBA formatting.

Click on Edit to open your thread, then highlight your code and click the # icon at the top of your post window. More information about these and other tags can be found here

(This thread should receive no further responses until this moderation request is fulfilled, as per Forum Rule 7)

RIP — d. 06/10/2022

If any of the responses have helped then please consider rating them by clicking the small star icon below the post.

Источник

Понравилась статья? Поделить с друзьями:
  • Intercept excel на русском
  • Intuit is it a word
  • Interactive word match games
  • Introduction to word structure
  • Interactive word games online