Application visible false excel

  1. 09-01-2011, 10:34 AM


    #1

    Solved: Application.Visible = False

    hi,

    i have a macro that i want to run but keep the workbook hidden, so as i don’t close it by accident.
    so i added
    [vba]Application.Visible = False
    [/vba].

    this works to hide the workbook however when i open another instance of Excel, my original workbook is restored. is there a way around this? any suggestions?

    thanks
    zach


  2. 09-01-2011, 10:47 AM


    #2

    [VBA]ActiveWindow.Visible = False[/VBA]


  3. 09-01-2011, 05:13 PM


    #3

    hi Kenneth,
    i will give that a try.

    thanks
    zach


  4. 09-02-2011, 08:19 AM


    #4

    kenneth,

    after applying
    [vba]

    ActiveWindow.Visible = False

    [/vba]
    if i have another Excel Workbook opened,
    how do i code it to
    [vba]

    ActiveWindow.Visible =True

    [/vba]

    how do i code it to bring focus back to the original workbook and unhide the sheet?

    thanks again
    zach


  5. 09-02-2011, 09:43 AM


    #5

    Untested:[VBA]Dim wb as Workbook
    Set wb=Workbooks(«TheNameHere.xls»)
    wb.Visible =True
    wb.activate
    wb.Sheet1.Visible = True[/VBA]

    You could use this this kind of thing to see if it is open or not:
    [VBA]
    Sub Test_IsWorkbookOPen()
    MsgBox IsWorkbookOpen(«Personal.xls»), , «Personal.xls Open?»
    MsgBox IsWorkbookOpen(«Personal.xlsb»), , «Personal.xlsb Open?»
    End Sub

    Function IsWorkbookOpen(stName As String) As Boolean
    Dim Wkb As Workbook
    On Error Resume Next ‘ In Case it isn’t Open
    Set Wkb = Workbooks(stName)
    If Not Wkb Is Nothing Then IsWorkbookOpen = True
    ‘Boolean Function assumed To be False unless Set To True
    End Function[/VBA]


  6. 09-02-2011, 11:21 AM


    #6

    hi Kenneth

    [vba]Dim wb As Workbook
    Set wb = Workbooks(«Hide Workbook Test.xls»)

    wb.Visible = True ‘Getting runtimme error 438
    wb.Activate
    wb.Sheet1.Visible = True[/vba]

    thanks for looking at this
    zach


  7. 09-02-2011, 11:35 AM


    #7

    Have it your way with Windows…

    [vba]Sub t()
    Dim wb As Workbook
    Set wb = Workbooks(ThisWorkbook.Name)
    wb.Worksheets(Sheet1.Name).Visible = xlSheetVeryHidden
    Windows(wb.Name).Visible = False
    Windows(wb.Name).Visible = True
    wb.Activate
    wb.Worksheets(Sheet1.Name).Visible = xlSheetVisible
    End Sub
    [/vba]


  8. 09-06-2011, 10:23 AM


    #8


 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

Всем доброй ночи! Не смог найти ответа на вопрос — Возможно ли при открытии книги оставить видимым например userform1 а приложение excel скрыть?

 

Игорь

Пользователь

Сообщений: 3631
Регистрация: 23.12.2012

да, возможно
Application.Visible = FALSE

пример можете здесь глянуть

 

Ivanok

Пользователь

Сообщений: 75
Регистрация: 01.01.1970

#3

04.08.2014 12:49:22

Игорь, Ваш пример хорош, но так будет лутше

Код
  If Application.Workbooks.Count = 1 Then 
    Application.Visible = False  
   Else 
    Windows(ThisWorkbook.Name).Visible = False 
 End If

Изменено: Ivanok04.08.2014 12:49:49

 

Игорь

Пользователь

Сообщений: 3631
Регистрация: 23.12.2012

Ivanok

, а чем так лучше?
тем, что код вылетит с ошибкой, будучи запущенным из надстройки (со скрытыми листами)?
или тем, что не выполнит поставленную задачу (скрыть приложение Excel), скрыв только одно окно одной книги?

всё просто делается
при запуске формы: Application.Visible = FALSE
при закрытии формы (по событию QueryClose): Application.Visible = TRUE

 

Ivanok

Пользователь

Сообщений: 75
Регистрация: 01.01.1970

если у вас будет открыто несколько книг … то все они будут скрытые …, а нужно скрыть только рабочую

 

The_Prist

Пользователь

Сообщений: 14181
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Ivanok

, в том и дело, что автор темы просил скрыть именно все приложение(что Игорь и продемонстрировал), а не только одну книгу с кодом. Где Вы вычитали про только рабочую книгу? Но в любом случае — автор придет и скажет что именно хотел.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Ivanok

Пользователь

Сообщений: 75
Регистрация: 01.01.1970

#7

04.08.2014 18:34:11

Цитата
ALFA пишет: при открытии книги
 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

#8

04.08.2014 18:40:52

Цитата
ALFA пишет: при открытии книги оставить видимым например userform1 а приложение excel скрыть

Ivanok, Вы правы в приведенной цитате, но зачем вырывать фразу из контекста? Результат — скрытие приложения эксель, а не книги эксель.  :)

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

I want to search through existing Excel files with a macro, but I don’t want to display those files when they’re opened by the code. Is there a way to have them open «in the background», so to speak?

Teamothy's user avatar

Teamothy

1,9903 gold badges15 silver badges24 bronze badges

asked Feb 23, 2009 at 23:08

notnot's user avatar

1

Not sure if you can open them invisibly in the current excel instance

You can open a new instance of excel though, hide it and then open the workbooks

Dim app as New Excel.Application
app.Visible = False 'Visible is False by default, so this isn't necessary
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(fileName)
'
' Do what you have to do
'
book.Close SaveChanges:=False
app.Quit
Set app = Nothing

As others have posted, make sure you clean up after you are finished with any opened workbooks

answered Feb 23, 2009 at 23:25

Patrick McDonald's user avatar

Patrick McDonaldPatrick McDonald

63.7k14 gold badges106 silver badges118 bronze badges

5

If that suits your needs, I would simply use

Application.ScreenUpdating = False

with the added benefit of accelerating your code, instead of slowing it down by using a second instance of Excel.

answered Aug 13, 2009 at 15:46

iDevlop's user avatar

iDevlopiDevlop

24.6k11 gold badges89 silver badges147 bronze badges

3

To open a workbook as hidden in the existing instance of Excel, use following:

    Application.ScreenUpdating = False
    Workbooks.Open Filename:=FilePath, UpdateLinks:=True, ReadOnly:=True
    ActiveWindow.Visible = False
    ThisWorkbook.Activate
    Application.ScreenUpdating = True

answered Jan 16, 2012 at 11:54

Ashok's user avatar

AshokAshok

1,0743 gold badges14 silver badges24 bronze badges

2

Using ADO (AnonJr already explained) and utilizing SQL is possibly the best option for fetching data from a closed workbook without opening that in conventional way. Please watch this VIDEO.

OTHERWISE, possibly GetObject(<filename with path>) is the most CONCISE way. Worksheets remain invisible, however will appear in project explorer window in VBE just like any other workbook opened in conventional ways.

Dim wb As Workbook

Set wb = GetObject("C:MyData.xlsx")  'Worksheets will remain invisible, no new window appears in the screen
' your codes here
wb.Close SaveChanges:=False

If you want to read a particular sheet, need not even define a Workbook variable

Dim sh As Worksheet
Set sh = GetObject("C:MyData.xlsx").Worksheets("MySheet")
' your codes here
sh.Parent.Close SaveChanges:=False 'Closes the associated workbook

answered Jan 22, 2021 at 16:03

Munim Rashid's user avatar

5

A much simpler approach that doesn’t involve manipulating active windows:

Dim wb As Workbook
Set wb = Workbooks.Open("workbook.xlsx")
wb.Windows(1).Visible = False

From what I can tell the Windows index on the workbook should always be 1. If anyone knows of any race conditions that would make this untrue please let me know.

answered Jul 13, 2016 at 18:40

wooobie's user avatar

wooobiewooobie

3452 silver badges12 bronze badges

Even though you’ve got your answer, for those that find this question, it is also possible to open an Excel spreadsheet as a JET data store. Borrowing the connection string from a project I’ve used it on, it will look kinda like this:

strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & objFile.Path & ";Extended Properties=""Excel 8.0;HDR=Yes"""
strSQL = "SELECT * FROM [RegistrationList$] ORDER BY DateToRegister DESC"

Note that «RegistrationList» is the name of the tab in the workbook. There are a few tutorials floating around on the web with the particulars of what you can and can’t do accessing a sheet this way.

Just thought I’d add. :)

answered Aug 13, 2009 at 15:58

AnonJr's user avatar

AnonJrAnonJr

2,7491 gold badge28 silver badges39 bronze badges

4

The problem with both iDevlop’s and Ashok’s answers is that the fundamental problem is an Excel design flaw (apparently) in which the Open method fails to respect the Application.ScreenUpdating setting of False. Consequently, setting it to False is of no benefit to this problem.

If Patrick McDonald’s solution is too burdensome due to the overhead of starting a second instance of Excel, then the best solution I’ve found is to minimize the time that the opened workbook is visible by re-activating the original window as quickly as possible:

Dim TempWkBk As Workbook
Dim CurrentWin As Window

Set CurrentWin = ActiveWindow
Set TempWkBk = Workbooks.Open(SomeFilePath)
CurrentWin.Activate      'Allows only a VERY brief flash of the opened workbook
TempWkBk.Windows(1).Visible = False 'Only necessary if you also need to prevent
                                    'the user from manually accessing the opened
                                    'workbook before it is closed.

'Operate on the new workbook, which is not visible to the user, then close it...

answered Jul 22, 2014 at 19:07

pstraton's user avatar

pstratonpstraton

1,04014 silver badges9 bronze badges

4

Open the workbook as hidden and then set it as «saved» so that users are not prompted when they close out.

Dim w As Workbooks

Private Sub Workbook_Open()
    Application.ScreenUpdating = False
    Set w = Workbooks
    w.Open Filename:="\serverPriceList.xlsx", UpdateLinks:=False, ReadOnly:=True 'this is the data file were going to be opening
    ActiveWindow.Visible = False
    ThisWorkbook.Activate
    Application.ScreenUpdating = True
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    w.Item(2).Saved = True 'this will suppress the safe prompt for the data file only
End Sub

This is somewhat derivative of the answer posted by Ashok.

By doing it this way though you will not get prompted to save changes back to the Excel file your reading from. This is great if the Excel file your reading from is intended as a data source for validation. For example if the workbook contains product names and price data it can be hidden and you can show an Excel file that represents an invoice with drop downs for product that validates from that price list.

You can then store the price list on a shared location on a network somewhere and make it read-only.

answered Jul 18, 2014 at 17:19

Pen123's user avatar

1

Open them from a new instance of Excel.

Sub Test()

    Dim xl As Excel.Application
    Set xl = CreateObject("Excel.Application")

    Dim w As Workbook
    Set w = xl.Workbooks.Add()

    MsgBox "Not visible yet..."
    xl.Visible = True

    w.Close False
    Set xl = Nothing

End Sub

You need to remember to clean up after you’re done.

answered Feb 23, 2009 at 23:43

guillermooo's user avatar

guillermoooguillermooo

7,83515 gold badges53 silver badges58 bronze badges

1

In excel, hide the workbooks, and save them as hidden. When your app loads them they will not be shown.

Edit: upon re-reading, it became clear that these workbooks are not part of your application. Such a solution would be inappropriate for user workbooks.

answered Feb 23, 2009 at 23:18

JohnW's user avatar

JohnWJohnW

2,9621 gold badge27 silver badges30 bronze badges

Есть событие открытия книги

Visual Basic
1
2
3
Private Sub Workbook_Open()
...
End Sub

сюда помести что то вроде:

Visual Basic
1
Моя_форма.Show

если хочешь спрятать окно excel и вывести только форму (как exe программа), то надо вписать:

Visual Basic
1
2
3
Application.Visible = False 'спрячет Excel
' или
ThisWorkbook.Worksheets(1).Visible=xlVeryHidden 'спрячет определенный лист

, и пользователь не сможет вывести его пока программно не выставить true

если у тебя форма которая выводит на лист данные, то лучше спрятать Application.ThisWorkbook (т.е. на котором выполняется код с формой)
и выводить на другом динамически созданном excel и рабочей книге.

Visual Basic
1
2
3
4
5
6
7
8
set xlApp = CreateObject(Excel.Application)
xlApp.Visible = True
xlApp.Workbook.Add Template:=xlWBASheet
with xlApp.Workbooks(1).Worksheets(1)
        .Caption = 'Новое приложение с одним листом'
        ...
        ThisWorkbook.Sheets(1).Range('A1').Copy Destination:= .Range('A1')
End with

что то вроде этого
тут много вохможностей.

При работе с Excel как с automation приложением полезно перевести это приложение в «абсолютно неинтерактивный режим». Сделать это можно создавая новый экземпляр приложения (new instance), а не подключаясь к уже запущенному, и установив следующие свойства:

  • Visible (ложь) — отображение окна приложения на экране
  • UserControl (ложь) — приложение запущено пользователем (или системой)
  • Interactive (ложь) — реагирование окна приложения на ввод от пользователя
  • DisplayAlerts (ложь) — отображение всяких предупреждающих сообщений (например, что данные будут утеряны)
  • ScreenUpdating (ложь) — перерисовывание окна приложения при изменении в нем информации
  • IgnoreRemoteRequests (истина) — игнорирование всех запросов от системы (в том числе на новые подключение как к automation server) — с этим нужно работать аккуратно, т.к. это параметр самого Excel (в Excel 2013Параметры Excel / Дополнительно / Игнорировать DDE-запросы от других приложений), и при аварийном завершении он останется установленным

По завершении формирования информации в Excel, если нужно приложение отобразить пользователю, то надо все эти свойства перевести в противоположное значение.

Пример:

Application.Visible = False
Application.UserControl = False
Application.Interactive = False
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.IgnoreRemoteRequests = True
      ................................
      ................................
      ................................
Application.IgnoreRemoteRequests = False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Interactive = True
Application.UserControl = True
Application.Visible = True

Понравилась статья? Поделить с друзьями:
  • Application version excel 2010
  • Application username in excel
  • Application type for excel
  • Application to open word documents
  • Application templates for microsoft word