Размер экрана vba excel

Ципихович Эндрю

1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

1

Как программно узнать разрешение экрана

15.01.2012, 15:25. Показов 22048. Ответов 26

Метки getdevicecaps (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте

Visual Basic
1
2
3
MsgBox$ _
            "Экран Вашего монитора имеет разрешение: " & GetSystemMetrics(0&) & "x" & GetSystemMetrics(1&) & vbCrLf & _
                                                       "Размер Вашего монитора: " & Application.UsableWidth & "x" & Application.UsableHeight, vbExclamation, "Информация"

Всё условно, реальный размер экрана монитора узнать можно?, у меня отображает MsgBox разрешение 1024*768, размер 769*529
А реально размер монитора — 370*305



0



Апострофф

Заблокирован

16.01.2012, 07:39

2

Не по теме:

Ципихович Эндрю, а вес монитора Вас не интересует:D
Для получения подобной инфы, мне кажется, нужна база по производителям, маркам и т.д. и т.п.
Возможно, я ошибаюсь?

Добавлено через 36 минут

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Option Explicit
Private Const LOGPIXELSX = 88 ' Logical pixels/inch in X
Private Const LOGPIXELSY = 90 ' Logical pixels/inch in Y
Private Const HORZRES = 8 ' Horizontal width in pixels
Private Const VERTRES = 10 ' Vertical width in pixels
Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hDc As Long, ByVal nIndex As Long) As Long
Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hDc As Long) As Long
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
 
Public Sub usbGetFormSize()
Dim x As Variant
Dim y As Variant
Dim hDc As Long, lngRetVal As Long
Dim varScreenX As Variant, varScreenY As Variant
Dim varPixToInchX As Variant, varPixToInchY As Variant
hDc = GetDC(0)
'Get the Screen size in pixels for X & Y
varScreenX = GetDeviceCaps(hDc, HORZRES)
varScreenY = GetDeviceCaps(hDc, VERTRES)
'Get the conversion of pixels/inch for X & Y
varPixToInchX = GetDeviceCaps(hDc, LOGPIXELSX)
varPixToInchY = GetDeviceCaps(hDc, LOGPIXELSY)
'Convert to миллиметры.
x = varScreenX / varPixToInchX * 25.4
y = varScreenY / varPixToInchY * 25.4
End Sub

Существует вот такой подход к решению,
но доверять ему я бы не стал!



3



1702 / 189 / 19

Регистрация: 20.11.2011

Сообщений: 281

16.01.2012, 10:41

3

Цитата
Сообщение от Апострофф
Посмотреть сообщение

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

Привет, Володь. Все гораздо проще. Рулетки будет достаточно:-) Производители часто неверно указывают параметры своих изделий.



0



6644 / 1511 / 169

Регистрация: 09.01.2010

Сообщений: 4,298

16.01.2012, 17:03

4

Цитата
Сообщение от kuklp
Посмотреть сообщение

Производители часто неверно указывают параметры своих изделий

как на коробках 0,25 Вт акустики пишут 300 Вт !!!



0



1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

16.01.2012, 20:01

 [ТС]

5

270*203 — неутешительно, против

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

А реально размер монитора — 370*305



0



Dragokas

16.01.2012, 20:12

Не по теме:

AIDA64 как-то мАгёт (раздел монитор).



0



1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

16.01.2012, 20:20

 [ТС]

7

может я не с того конца зашёл, тема такая есть на работе монитор 24″, широкоэкранный, сделаешь всё там, про формы говорю, делаю большими, домой придёшь, на 19″ не очень удобно. Вот программно инициализацию активацию формы хочу править- как лучше поступить?



0



gaw

16.01.2012, 20:53

Не по теме:

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

как лучше поступить

на работе — работать, а формы — дома, ну если конечно это Ваша работа — формы делать, тогда где то поменять монитор — самое то



0



Апострофф

Заблокирован

16.01.2012, 20:58

9

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

Вот программно инициализацию активацию формы хочу править- как лучше поступить?

Не с размеров экрана, а с разрешения надо начинать!

‘Get the Screen size in pixels for X & Y
varScreenX = GetDeviceCaps(hDc, HORZRES)
varScreenY = GetDeviceCaps(hDc, VERTRES)



0



1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

16.01.2012, 21:12

 [ТС]

10

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

разрешение 1024*768

и что это даёт?
есть разрешение монитора, есть форма, как её ужимать правильно, до каких пределов?



0



1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

18.01.2012, 05:17

 [ТС]

11

апну тему

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

и что это даёт?
есть разрешение монитора, есть форма, как её ужимать правильно, до каких пределов?



0



Апострофф

Заблокирован

18.01.2012, 10:30

12

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

реальный размер экрана монитора узнать можно?

Цитата
Сообщение от Diskretor
Посмотреть сообщение

AIDA64 как-то мАгёт (раздел монитор).

Нашел полный список констант для GetDeviceCaps — всё оказалось до смешного просто
Но по прежнему врёт!

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Option Explicit
 
Private Const DRIVERVERSION  As Long = 0     'Версия драйвера
Private Const TECHNOLOGY     As Long = 2     'Классификация устройства
 
Private Const HORZSIZE       As Long = 4     '!!!Размер по горизонтали в мм.
Private Const VERTSIZE       As Long = 6     '!!!Размер по вертикали в мм.
 
Private Const HORZRES        As Long = 8     'Размер по горизонтали в точках
Private Const VERTRES        As Long = 10    'Размер по вертикали в точках
Private Const BITSPIXEL      As Long = 12    'Кол-во бит на точку
Private Const PLANES         As Long = 14    'Number of planes
Private Const NUMBRUSHES     As Long = 16    'Number of brushes the device has
Private Const NUMPENS        As Long = 18    'Number of pens the device has
Private Const NUMMARKERS     As Long = 20    'Number of markers the device has
Private Const NUMFONTS       As Long = 22    'Number of fonts the device has
Private Const NUMCOLORS      As Long = 24    'Макс. кол-во возможных цветов
Private Const PDEVICESIZE    As Long = 26    'Size required for device descripto
Private Const CURVECAPS      As Long = 28    'Curve capabilities
Private Const LINECAPS       As Long = 30    'Line capabilities
Private Const POLYGONALCAPS  As Long = 32    'Polygonal capabilities
Private Const TEXTCAPS       As Long = 34    'Text capabilities
Private Const CLIPCAPS       As Long = 36    'Clipping capabilities
Private Const RASTERCAPS     As Long = 38    'Bitblt capabilities
Private Const ASPECTX        As Long = 40    'Length of the X leg
Private Const ASPECTY        As Long = 42    'Length of the Y leg
Private Const ASPECTXY       As Long = 44    'Length of the hypotenuse
Private Const SHADEBLENDCAPS As Long = 45    'Shading and blending caps (IE5)
Private Const LOGPIXELSX     As Long = 88    'Logical pixels/inch in X
Private Const LOGPIXELSY     As Long = 90    'Logical pixels/inch in Y
Private Const SIZEPALETTE    As Long = 104   'Number of entries in physical palette
Private Const NUMRESERVED    As Long = 106   'Number of reserved entries in palette
Private Const COLORRES       As Long = 108   'Количество цветов
Private Const VREFRESH       As Long = 116   'Текущий рефрешь по вертикали в Гц
                                             '(только для монитора)
Private Const DESKTOPVERTRES As Long = 117   'Размер десктопа по горизонтали
Private Const DESKTOPHORZRES As Long = 118   'Размер десктопа по вертикали
Private Const BLTALIGNMENT   As Long = 119   'Preferred blt alignment
 
Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hDc As Long, ByVal nIndex As Long) As Long
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
 
Public Sub ScreenSize()
MsgBox GetDeviceCaps(GetDC(0), 4) & " X " & GetDeviceCaps(GetDC(0), 6) & " mm"
End Sub



2



6169 / 934 / 309

Регистрация: 25.02.2011

Сообщений: 1,359

Записей в блоге: 1

18.01.2012, 11:27

13

Цитата
Сообщение от Апострофф
Посмотреть сообщение

Нашел полный список констант для GetDeviceCaps — всё оказалось до смешного просто
Но по прежнему врёт!

У меня практически не врет, измерил линейкой, расхождение в пару милиметров.
Только не понятно, зачем нужен именно размер в миллиметрах, когда нужно ориентироваться на разрешение экрана.
Какая разница 17 или 22 дюймовый монитор, если разрешение экрана и там и там 1024х768 и форма одинаково будет смотрется на обоих мониторах (относительно других объектов)



0



gaw

6644 / 1511 / 169

Регистрация: 09.01.2010

Сообщений: 4,298

18.01.2012, 11:45

14

Visual Basic
1
2
3
4
5
6
Private Sub Form_Load()
k = 0.5
Me.Width = k * Screen.Width
Me.Height = k * Screen.Height
Me.Move (Screen.Width - Me.Width) / 2, (Screen.Height - Me.Height) / 2
End Sub



2



Апострофф

Заблокирован

18.01.2012, 14:49

15

Цитата
Сообщение от gaw
Посмотреть сообщение

Me.Width = k * Screen.Width
Me.Height = k * Screen.Height
Me.Move (Screen.Width — Me.Width) / 2, (Screen.Height — Me.Height) / 2
End Sub

Идея понятна, но в VBA нет объекта Screen,
да и все контролы на форме тоже надо масштабировать.
Всё это уже делалось неоднократно, но у ТС проблемы с поиском, кажется



1



6644 / 1511 / 169

Регистрация: 09.01.2010

Сообщений: 4,298

18.01.2012, 16:38

16

Цитата
Сообщение от Апострофф
Посмотреть сообщение

Идея понятна, но в VBA нет объекта Screen

виноват, — исправлюсь ==> это Ципихович Ендрю наверное онлайн гипнозом обладает



0



Ципихович Эндрю

1508 / 478 / 56

Регистрация: 10.04.2009

Сообщений: 8,008

18.01.2012, 19:11

 [ТС]

17

Цитата
Сообщение от m-ch
Посмотреть сообщение

Только не понятно, зачем нужен именно размер в миллиметрах, когда нужно ориентироваться на разрешение экрана.

так я и спрашиваю как? знаю разрешение, как далее считать?

Цитата
Сообщение от Апострофф
Посмотреть сообщение

MsgBox GetDeviceCaps(GetDC(0), 4) & » X » & GetDeviceCaps(GetDC(0), 6) & » mm»

выдаёт 380*285 против

Цитата
Сообщение от Ципихович Эндрю
Посмотреть сообщение

А реально размер монитора — 370*305

ну более мене похоже на правду, замерю завтра у других

Добавлено через 5 минут
Апострофф, зачем людей пугать если хватает этого:

Visual Basic
1
2
3
4
5
6
7
8
Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hDc As Long, ByVal nIndex As Long) As Long
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
 
Public Sub ScreenSize()
 
    MsgBox GetDeviceCaps(GetDC(0), 4) & " X " & GetDeviceCaps(GetDC(0), 6) & " mm"
 
End Sub

я имею ввиду — константы для общего развития?



0



126 / 1 / 1

Регистрация: 15.11.2011

Сообщений: 80

01.01.2013, 22:45

18

Столкнулась с такой же проблемой как и автор темы.

Но так и не вижу решения.
Мне тоже надо определить разрешение экрана, но без «user32».
Помогите



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

01.01.2013, 23:40

19

Не хотите «user32» (почему?!) — используйте WMI (это медленнее)

Visual Basic
1
2
3
4
5
6
7
8
With GetObject("winmgmts:\.rootcimv2")
    For Each x In .ExecQuery("Select * From Win32_DisplayConfiguration")
        MsgBox "Horizontal resolution: " & x.PelsWidth
        MsgBox "Vertical resolution: " & x.PelsHeight
        MsgBox "Name: " & x.DeviceName
        MsgBox "Color depth: " & x.BitsPerPel
    Next
End With

Утянуто с http://blogs.technet.com/b/hey… puter.aspx и слегка переработано



2



126 / 1 / 1

Регистрация: 15.11.2011

Сообщений: 80

02.01.2013, 00:17

20

Цитата
Сообщение от Казанский
Посмотреть сообщение

Не хотите «user32» (почему?!) — используйте WMI (это медленнее)[

на 64-битной системе все эти библиотеки не работают.
Ваш пример заработал, спасибо



0



Содержание

  1. Vba excel размеры экрана
  2. VBA Excel. Свойство Application.WindowState
  3. Свойство Application.WindowState
  4. Константы XlWindowState
  5. Пример кода с WindowState
  6. Resize a UserForm with VBA or Windows API
  7. Windows API Solution
  8. How does it work?
  9. Setting up the Windows API code
  10. Setting up the UserForm
  11. VBA only solution
  12. How does it work?
  13. Setting up the UserForm
  14. Download the example file
  15. Свойства Height, Width
  16. Синтаксис
  17. Замечания
  18. См. также
  19. Поддержка и обратная связь

Vba excel размеры экрана

200?’200px’:»+(this.scrollHeight+5)+’px’);»>
Option Explicit
Public FormIsOn As Boolean
Public Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Public Declare Function GetSystemMetrics Lib «user32.dll» (ByVal nIndex As Long) As Long
Public Declare Function GetDesktopWindow Lib «user32» () As Long
Public Declare Function GetWindowRect Lib «user32» (ByVal hWnd As Long, lpRect As RECT) As Long

Public Function ScreenWidth() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenWidth = RRight ‘* Screen.TwipsPerPixelX
End Function

Public Function ScreenHeight() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenHeight = R.Bottom * Screen.TwipsPerPixelY
End Function

Sub test()
Dim x As Integer, y As Integer
x = GetSystemMetrics(0)
y = GetSystemMetrics(1)
MsgBox «Ширина экрана:» & x & » : » & y
End Sub

200?’200px’:»+(this.scrollHeight+5)+’px’);»>
Option Explicit
Public FormIsOn As Boolean
Public Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Public Declare Function GetSystemMetrics Lib «user32.dll» (ByVal nIndex As Long) As Long
Public Declare Function GetDesktopWindow Lib «user32» () As Long
Public Declare Function GetWindowRect Lib «user32» (ByVal hWnd As Long, lpRect As RECT) As Long

Public Function ScreenWidth() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenWidth = RRight ‘* Screen.TwipsPerPixelX
End Function

Public Function ScreenHeight() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenHeight = R.Bottom * Screen.TwipsPerPixelY
End Function

Sub test()
Dim x As Integer, y As Integer
x = GetSystemMetrics(0)
y = GetSystemMetrics(1)
MsgBox «Ширина экрана:» & x & » : » & y
End Sub

200?’200px’:»+(this.scrollHeight+5)+’px’);»>
Option Explicit
Public FormIsOn As Boolean
Public Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Public Declare Function GetSystemMetrics Lib «user32.dll» (ByVal nIndex As Long) As Long
Public Declare Function GetDesktopWindow Lib «user32» () As Long
Public Declare Function GetWindowRect Lib «user32» (ByVal hWnd As Long, lpRect As RECT) As Long

Public Function ScreenWidth() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenWidth = RRight ‘* Screen.TwipsPerPixelX
End Function

Public Function ScreenHeight() As Single
Dim R As RECT
GetWindowRect GetDesktopWindow(), R
ScreenHeight = R.Bottom * Screen.TwipsPerPixelY
End Function

Sub test()
Dim x As Integer, y As Integer
x = GetSystemMetrics(0)
y = GetSystemMetrics(1)
MsgBox «Ширина экрана:» & x & » : » & y
End Sub

Источник

VBA Excel. Свойство Application.WindowState

Установка состояния окна приложения Excel из кода VBA с помощью свойства Application.WindowState. Сворачивание и разворачивание окна. Чтение данных о состоянии окна.

Свойство Application.WindowState

Состояние окна приложения Excel задается константой из коллекции XlWindowState, при чтении информации о состоянии окна — свойство Application.WindowState возвращает числовое значение константы.

Свойство Application.WindowState позволяет развернуть окно приложения Excel из кода VBA на весь экран — до максимального размера, свернуть окно «в иконку» или задать ему нормальные размеры, установленные ранее, развернув из свернутого или свернув из максимального.

Синтаксис свойства WindowState объекта Application:

Константы XlWindowState

Константы из коллекции XlWindowState:

Константа Значение Описание
xlMaximized -4137 Максимальное окно (развернуто на весь экран)
xlMinimized -4140 Минимальное окно (свернуто «в иконку»)
xlNormal -4143 Нормальное окно (размеры, установленные ранее)

Пример кода с WindowState

Пример записи и чтения свойства Application.WindowState:

Попробуйте по очереди задавать разные константы свойству Application.WindowState и смотрите, какое значение будет считано. У меня получились удивительные результаты при выполнении строк кода по очереди, как в примере:

  • Application.WindowState = xlMinimized — MsgBox возвращает совсем не -4140;
  • после первого запуска Application.WindowState = xlNormal — окно приложения разворачивается на весь экран, после второго запуска — переходит к нормальному состоянию.

Не удалось мне добиться значения -4140 и при минимизации окна вручную, разместив предварительно следующий код в модуль книги:

Источник

Resize a UserForm with VBA or Windows API

When creating a VBA UserForm, we generally set it to a specific size. Most other forms and windows within the Excel and Windows environments do not have a fixed sized; they can be resized by the user. With a bit of coding magic, we can achieve a similar resizing effect for our VBA UserForms. This post will show you how.

There are two solutions presented below, a Windows API method and a VBA only method. Of the two, the Windows API solution has a smoother, more integrated feel for the user, but it will only work on Windows. If your code is expected to work on Windows and Mac, then using the VBA solution is the better option.

Windows API Solution

Windows API codes make use of special functions which are not part of Excel or VBA, but part of the main Windows application. The topic of Windows API codes is too big to discuss here, but by following the instructions below you can still get the code working, even if you don’t have a full understanding of why it works.

Remember, Windows API codes will only work on Windows.

How does it work?

A brief overview of how the process works will help with understanding what the code below does.

  1. Change the Windows setting to enable the UserForm to be resized.
  2. On the UserForm use the Resize event to capture when the form is resized.
  3. The objects’ size or position changes after each resize event.

Setting up the Windows API code

Copy the following code into a new standard module. It must be included at the top of the module before any functions or subprocedures, but below the Option Explicit statement (if there is one).

This following code must be included within the same module as the code above but does not need to be directly below it.

The two code segments above create a reusable procedure which we can use to toggle the UserForm’s resize setting on or off. Anytime we want to turn on resizing for a UserForm, use the following:

To turn off resizing, use the following

Just replace myUserForm with the name of your form, or use Me if within the UserForm’s code module.

Setting up the UserForm

To illustrate the process, I’ve created a UserForm which looks like this:

There are just two elements:

  • A ListBox called lstListBox
  • A Button called cmdClose

Both of these elements should change when then UserForm resizes. lstListBox should change in size, but not in position while the cmdClose will change in position but not in size. To enable this to happen we need to know the position of these objects from the bottom and right of the UserForm. Provided we keep the same distance from the bottom and right it will appear that these items are moving in sync with the UserForm.

The code below must be included within the UserForm’s code module to function correctly.

To capture the initial bottom and right positions of the ListBox and Button, we set up some Private variables to hold the values.

Now let’s set up what happens when the UserForm initializes.

Firstly, resizing is enabled by calling the code created in the Windows API section above. Secondly, we store the position of the objects in the private variables created above.

Next, using the UserForm’s resize event, we change the size/position of ListBox and the Button:

  • lstListBox changes height and width
  • cmdCloses changes top and left position

That is it. You’ve now got the code you need. So fire up the UserForm and start resizing.

When the mouse hovers over the edge of the UserForm, the icon changes, just click and drag. With this method, resizing can happen on any side of the UserForm.

VBA only solution

The VBA solution makes use of mouse events to trigger when to change the height and width of the UserForm. Personally, I think it’s not as smooth as the Window API solution, but it is much easier to understand and can be used on a Mac too.

How does it work?

The VBA solution uses a different method of application to the Window API solution.

  1. The UserForm contains an object which when clicked records the position of the mouse.
  2. As the mouse moves, the UserForm and it’s objects are repositioned or resized based on the new mouse position.
  3. When the mouse button is released, movement ceases to adjust the size.

Setting up the UserForm

To illustrate the process, I have created anotherUserForm; it looks like this:

There are just three elements:

  • ListBox called lstListBox
  • Button called cmdClose
  • Label called lblResizer

The lblResizer is a label which includes the “y” character from the Wingdings 3 font set. This displays as a small triangle in the bottom right corner to show the user where to click to resize the window. The Color and MousePointer properties are set as follows:

All of these elements, along with the UserForm itself will need to change when the mouse is clicked and moved whilst over the lblResizer object.

All the code must be contained within the UserForm’s code module.

We will set up some Private variables to hold the mouse position and click status, along with the minimum allowed window size.

When initializing the UserForm, the code below will place the lblResizer into the bottom right corner, and set the minimum permitted window size.

The following code triggers when the mouse clicks on the lblResizer icon. The code records that the icon has been clicked and the position of the mouse at that moment.

The following code triggers when the mouse moves while over the lblResizer.

Firstly, it will check that the window is larger than the minimum permitted size, and that mouse has been clicked. If both of these are True, the UserForm and the objects are re-positioned or resized based on the size of the mouse movement.

The following code triggers when the mouse button is released; the mouse movement ceases to resize the UserForm.

That is it; we’re good to go. Open up the UserForm and start resizing.

In this example, the UserForm only resizes when the mouse clicks on the icon in the bottom right. We could add the ability to expand from the right, bottom, or left by using objects positioned just inside the edges of the UserForm.

Download the example file

Want to see these examples working? Th e n download the example file.

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).

Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:

Источник

Свойства Height, Width

Высота и ширина объекта в пунктах.

Синтаксис

object. Высота [= одиночный ]
object. Width [= Single ]

Синтаксис свойств Height и Width состоит из следующих частей:

Part Описание
object Обязательно. Допустимый объект.
Одинарное с плавающей точкой Необязательный параметр. Числовое выражение, определяющее размеры объекта.

Замечания

Значения свойств Height и Width автоматически обновляются при перемещении или изменении размеров элементов управления. При изменении размера элемента управления свойство Height или Width сохраняет новую высоту или ширину, а свойство OldHeight или OldWidth — предыдущую высоту или ширину. Если свойству Left или Top присвоено значение меньше нуля, соответствующее значение будет использоваться для расчета высоты или ширины элемента управления, однако при этом определенная его часть не будет отображаться.

Если вы перемещаете элемент управления по форме, значения его свойств Height или Width изменяются только в том случае, если одновременно с этим вы изменяете его размер. Значения свойств Left и Top изменяются в соответствии с изменением позиции элемента относительно границ формы.

Свойства Height и Width не могут иметь отрицательные значения. В большинстве систем рекомендуемый диапазон этих значений составляет от 0 до +32 767. В некоторых конфигурациях поддерживаются и более высокие значения.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

What is Display Resolution?

The number of Pixels displayed in your Monitor is called Screen Resolution.

It is represented as how many Pixels displayed in Screen height x Screen width. To get the screen height and width use these codes as per your programming language. The computer or mobile devices do not have standard screen resolutions.

It varies with every manufacturer and every computer model. So, the developers have to design their application to be compatible with the user’s device resolution limits.

Be it an application developer or a Web developer, everyone have to use any of these codes at some point of time.

1. What is my Screen Resolution? – VBA using Windows API

The VBA code below retrieves screen resolution parameters using 2 different methods, both using the Win api functions.

Option Explicit
'For Method 1
Private Declare Function GetClientRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
Private Declare Function GetDesktopWindow Lib "user32" () As Long
Private Type RECT
        Left As Long
        Top As Long
        Right As Long
        Bottom As Long
End Type
'For Method 2
Private Declare Function GetSystemMetrics Lib "user32.dll" (ByVal nIndex As Long) As Long
Const SM_CXSCREEN = 0
Const SM_CYSCREEN = 1

Private Sub VBA_Screen_Resolution()
    'Method 1
    Dim rScreen As RECT
    GetClientRect CLng(GetDesktopWindow()), rScreen
    ThisWorkbook.Sheets(1).Cells(1, 1) = "Left"
    ThisWorkbook.Sheets(1).Cells(2, 1) = "Right"
    ThisWorkbook.Sheets(1).Cells(3, 1) = "Top"
    ThisWorkbook.Sheets(1).Cells(4, 1) = "Bottom"
    
    ThisWorkbook.Sheets(1).Cells(1, 2) = rScreen.Left
    ThisWorkbook.Sheets(1).Cells(2, 2) = rScreen.Right
    ThisWorkbook.Sheets(1).Cells(3, 2) = rScreen.Top
    ThisWorkbook.Sheets(1).Cells(4, 2) = rScreen.Bottom
    
    'Method 2
    MsgBox "Screen Resolution - " & GetSystemMetrics(SM_CXSCREEN) & " x " & GetSystemMetrics(SM_CYSCREEN)

End Sub

Note: Function used in method 2 in above example can be used in C Programming to get screen width & height. Include Windows.h and then use the function with same parameters in your C program.

2. Get Display resolution in Javascript

It is easy to get screen width and height with Javascript. You just need to use the ‘Screen’ Object as in below code sample.

var wscr = “Screen Width: “ + screen.width
var hscr = “Screen Height: “ + screen.height
var awscr = “Screen Width excluding Taskbar: “ + screen.availWidth
var ahscr = “Screen Width excluding Taskbar: “ + screen.availHeight

The above can be tested right from your internet browser Firefox, Chrome or IE. To test it in Firefox, press Ctrl + Shift + q, then choose ‘Console’. Type this command ‘console.log (wscr);’ and press enter.

Firefox console will display the screen width.

3. Find Windows Screen Height & Width from Command Prompt

Open command prompt and type this command. Just so simplest of all.

wmic desktopmonitor get screenheight, screenwidth
'Or this command to open the windows screen resolution display settings.
rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,3

By now you would be able to answer ‘What is Display resolution’ of your computer using the above free codes. If you require the coding in any specific programming language, please leave us a comment.

ExcelYou may develop an Excel application that needs to adjust itself depending on the video resolution of the user. For

example, you might have an application that requires a certain range to show so you’ll need to adjust Excel’s zoom factor.

Here is a way by using GetSystemMetrics API function of windows :

CODE :

Declare Function GetSystemMetrics32 Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long 

Sub DisplayScreenResolution() 
    Dim lngWidth            As Long
    Dim lngHeight           As Long    

    lngWidth = GetSystemMetrics32(0) ' width in points
    lngHeight = GetSystemMetrics32(1) ' height in points

    MsgBox Format(lngWidth, "#,##0") & " x " & Format(lngHeight, "#,##0"), vbInformation, "Screen Resolution (width x height)"
    
End Sub

 

dtrey

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

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

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

 

Kuzmich

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

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

#2

21.05.2014 22:13:01

Код
Private Sub UserForm_Initialize()
    Me.Height = Int(0.98 * ActiveWindow.Height)
    Me.Width = Int(0.98 * ActiveWindow.Width)
End Sub

 
 

anvg

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

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

Excel 2016, 365

Доброе время суток.

Может всё-таки освоить поиск

Не зависимо от размера монитора и установленного разрешения, вывести форму на весь экран можно так

?
Успехов.
P. S. лучше использовать в UserForm_Activate, в UserForm_Initialize будет ругаться.

Изменено: anvg22.05.2014 06:19:53

 

dtrey

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

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

#4

22.05.2014 09:41:38

Нашел вот такой код :

Код
Private Sub UserForm_Initialize()
    With Application
        Width = .Width
        Height = .Height
    End With
End Sub 

работает на ура.
Но проблема появилась другая, все содержимое UserForm потянулось влево экрана.
Подскажите, как автоматически центровать содержимое UserForm ?

 

JayBhagavan

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

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

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

dtrey, во-первых, здравствуйте ;) , во-вторых код в тэгах должен быть, в-третьих, одна тема — один вопрос. Изучайте и применяйте правила форума. Они лёгкие.
ПС Модераторы, простите, если отбираю Ваш хлеб. Хотел помочь.  :oops:

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

 

Johny

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

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

Выберите в свойствах формы: StartUpPosition => 2 — CenterScreen.

There is no knowledge that is not power

 

anvg

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

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

Excel 2016, 365

#7

22.05.2014 11:00:44

Цитата
StartUpPosition => 2 — CenterScreen
Цитата
With Application
Width = .Width
Height = .Height

А если Excel не на весь экран? Или у ТС задача закрыть своей формой Excel?

 

vikttur

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

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

StartUpPosition задает позицию. Если форма растянута на весь экран, то она и так по центру.
Элементы на форме так и останутся на месте, т.е. ближе к левому верхнему углу.

Кто объяснит по коду Кузьмича.
Почему форма растягивается по горизонтали на весь экран, по вертикали — нет?
На моем ноуте (монитор16/9) на весь экран:
Me.Height = Int(1.4 * ActiveWindow.Height)
Монитор менять на 3/4?  :)

 

anvg

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

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

Excel 2016, 365

#9

22.05.2014 11:07:47

Цитата
Монитор менять на 3/4?
Код
 Application.Height - ActiveWindow.Height

Вот и вся разница.

 

vikttur

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

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

Окно Excel на весь экран, форма не хочет.

 

Johny

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

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

#11

22.05.2014 11:10:12

Цитата
anvg пишет: А если Excel не на весь экран? Или у ТС задача закрыть своей формой Excel?
Цитата
dtrey пишет: UserFormа автоматически меняла свой размер под размер монитора.

А если завтра дождь пойдёт?

There is no knowledge that is not power

 

anvg

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

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

Excel 2016, 365

#12

22.05.2014 11:14:39

Цитата
Окно Excel на весь экран, форма не хочет.

Так и надо же к Excel и привязываться

Код
Me.Width = Application.Width
Me.Height = Application.Height 
Цитата
А если завтра дождь пойдёт?

Тогда вставить изменение размера формы в событие UserForm_Layout

 

vikttur

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

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

#13

22.05.2014 11:17:41

Цитата
anvg пишет: надо же к Excel и привязываться

Это ясно.

Цитата
vikttur пишет: Кто объяснит по коду Кузьмича

Почему не растягивается на все окно? Все-таки влияние размера монитора? Если бы это, то должно быть наоборот — полный разворот по вертикали.

 

anvg

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

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

Excel 2016, 365

Окно листа книги же не занимает весь экран? Вот и форма то же.

 

vikttur

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

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

Окно-то активное — не  на весь экран!
Application со всякими лентами-панелями — это не активное окно.
Подвел стереотип мышления: окно=экран
Спасибо, дошло.

 

dtrey

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

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

#16

22.05.2014 11:50:17

Цитата
Johny пишет: Выберите в свойствах формы: StartUpPosition => 2 — CenterScreen.

не помогает(

 

vikttur

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

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

#17

22.05.2014 11:56:15

Сообщение №8 читали? И не поможет. Элементы формы просто так не переместятся.
Нужно или менять масштаб (для каждого!), или менять позицию (для каждого Frame, например).
Смиритесь.

Понравилась статья? Поделить с друзьями:
  • Размер штампа гост а4 word
  • Размер шрифта в word в пикселах
  • Размер шрифтов в текстовом редакторе ms word устанавливается в
  • Размер шрифта word в миллиметрах
  • Размер шрифта сносок word