Excel vba points to pixels

Get our FREE VBA eBook of the 30 most useful Excel VBA macros.

Automate Excel so that you can save time and stop doing the jobs a trained monkey could do.

Claim your free eBook


VBA Code Snippets

It is frustrating that Excel, PowerPoint and Word work natively using a measurement known as points.  However, measurements within the standard application menus are set in centimeters or inches.  This can be seen when setting the position and size of a shape in PowerPoint through the standard menus.

PowerPoint measures in Cms

Measurements in standard menus are in Centimeters

Yet, when using a macro to retrieve the position of that same shape, it displays the value in points.

PowerPoint measures in Points

Measurements for VBA are in Points

Below is the PowerPoint VBA Code to show the dimensions of the active shape:

Sub getShapeSizes()

Dim msgText As String
msgText = "Top: " & ActiveWindow.Selection.ShapeRange.Top & vbNewLine
msgText = msgText & "Left: " & ActiveWindow.Selection.ShapeRange.Left & vbNewLine
msgText = msgText & "Height: " & ActiveWindow.Selection.ShapeRange.Height & vbNewLine
msgText = msgText & "Width: " & ActiveWindow.Selection.ShapeRange.Width & vbNewLine

MsgBox msgText

End Sub

Whether the displayed measurements are in centimeters or inches is set through the Control Panel for PowerPoint.  For Excel, the default is also set through the Control panel, but this can be changed to be non-default within the Excel options. File -> Options -> Advanced -> Display -> Ruler Units.

Change Excel Unit of Measure

Converting from Inches or Centimeters to Points

Converting from inches or centimeters into points is reasonably straightforward, as there are 72 points to an inch or 28.35 points to a centimeter (rounded to 2 decimal places).  Microsoft has provided two useful VBA function to make this conversion

Convert from Inches to Points

Dim valueInches As Double
Dim valuePoints As Double
valueInches = 25
valuePoints = Application.InchesToPoints(valueInches)
Debug.Print valuePoints

Convert from Centimeters to Points

Dim valueCentimeters As Double
Dim valuePoints As Double
valueCentimeters = 25
valuePoints = Application.CentimetersToPoints(valueCentimeters)
Debug.Print valuePoints

Convert from Points to Centimeters

Dim valuePoints As Double
Dim valueCentimeters As Double
valuePoints = 50
valueCentimeters = valuePoints / Application.CentimetersToPoints(1)
Debug.Print valueCentimeters

Convert from Points to Inches

Dim valuePoints As Double
Dim valueInches As Double
valuePoints = 700
valueInches = valuePoints / Application.InchesToPoints(1)
Debug.Print valueInches

Converting from Points to Pixels

What about Pixels?  Whilst Pixels may seem to be an understandable unit of measure for the purposes of controlling positions of objects, it’s not as useful as you might expect.

The number of pixels will depend on a variety of factors, such as screen resolution used for each monitor.  However, if you are desperate to convert points to pixels the following VBA code could be used.

Dim valuePoints As Long
Dim valuePixels As Long
valuePoints = 500
valuePixels = Application.ActiveWindow.PointsToScreenPixelsX(valuePoints)
Debug.Print "X axis Pixels: " & valuePixels
valuePixels = Application.ActiveWindow.PointsToScreenPixelsY(valuePoints)
Debug.Print "Y axis Pixels: " & valuePixels

Headshot Round

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:

This repository has been archived by the owner on Aug 31, 2018. It is now read-only.

Permalink

Cannot retrieve contributors at this time

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

Window.PointsToScreenPixelsX Method (Excel)

vbaxl10.chm356129

vbaxl10.chm356129

excel

Excel.Window.PointsToScreenPixelsX

b637ae59-30fe-a5cd-2c0d-d9cb63c77d84

06/08/2017

Window.PointsToScreenPixelsX Method (Excel)

Converts a horizontal measurement from points (document coordinates) to screen pixels (screen coordinates). Returns the converted measurement as a Long value.

Syntax

expression . PointsToScreenPixelsX( Points )

expression A variable that represents a Window object.

Parameters

Name Required/Optional Data Type Description
Points Required Long The number of points horizontally along the top of the document window, starting from the left.

Return Value

Long

Example

This example determines the height and width (in pixels) of the selected cells in the active window and returns the values in the lWinWidth and lWinHeight variables.

With ActiveWindow 
 lWinWidth = _ 
 .PointsToScreenPixelsX(.Selection.Width) 
 lWinHeight = _ 
 .PointsToScreenPixelsY(.Selection.Height) 
End With

See also

Concepts

Window Object

PointsToScreenPixelsY Method

Converts a vertical measurement from points (document coordinates) to screen pixels (screen coordinates). Returns the converted measurement as a Long value.

expression.PointsToScreenPixelsY(Points)

expression   An expression that returns a Window object.

Points   Required Long. The number of points vertically along the left edge of the document window, starting from the top.

Example

This example determines the height and width (in pixels) of the selected cells in the active window and returns the values in the lWinWidth and lWinHeight variables.

With ActiveWindow
    lWinWidth = _
        .PointsToScreenPixelsX(.Selection.Width)
    lWinHeight = _
        .PointsToScreenPixelsY(.Selection.Height)
End With

Содержание

  1. Global.PointsToCentimeters method (Word)
  2. Syntax
  3. Parameters
  4. Return value
  5. Example
  6. See also
  7. Support and feedback
  8. Метод Application.PointsToCentimeters (Word)
  9. Синтаксис
  10. Параметры
  11. Возвращаемое значение
  12. Пример
  13. См. также
  14. Поддержка и обратная связь
  15. Метод Global.PointsToCentimeters (Word)
  16. Синтаксис
  17. Параметры
  18. Возвращаемое значение
  19. Пример
  20. См. также
  21. Поддержка и обратная связь
  22. Application.PointsToCentimeters method (Word)
  23. Syntax
  24. Parameters
  25. Return value
  26. Example
  27. See also
  28. Support and feedback
  29. VBA: Convert centimeters, inches & pixels to points
  30. Converting from Inches or Centimeters to Points
  31. Convert from Inches to Points
  32. Convert from Centimeters to Points
  33. Convert from Points to Centimeters
  34. Convert from Points to Inches
  35. Converting from Points to Pixels

Global.PointsToCentimeters method (Word)

Converts a measurement from points to centimeters (1 centimeter = 28.35 points). Returns the converted measurement as a Single.

Syntax

expression. PointsToCentimeters ( _Points_ )

expression A variable that represents a ‘Global’ object. Optional.

Parameters

Name Required/Optional Data type Description
Points Required Single The measurement, in points.

Return value

Example

This example converts a measurement of 30 points to the corresponding number of centimeters.

This example converts the value of the variable sngData (a measurement in points) to centimeters, inches, lines, millimeters, or picas, depending on the value of the variable intUnit (a value from 1 through 5 that indicates the resulting unit of measurement).

See also

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.

Источник

Метод Application.PointsToCentimeters (Word)

Преобразует измерение из точек в сантиметры (1 сантиметр = 28,35 точек). Возвращает преобразованное измерение в виде единицы.

Синтаксис

выражение. PointsToCentimeters ( _Points_ )

выражение: переменная, представляющая объект Application. Необязательный параметр.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Points Обязательный Single Измерение в точках.

Возвращаемое значение

Пример

В этом примере значение 30 точек преобразуется в соответствующее число сантиметров.

В этом примере значение переменной sngData (измерение в точках) преобразуется в сантиметры, дюймы, линии, миллиметры или пика в зависимости от значения переменной intUnit (значение от 1 до 5, указывающее результирующая единица измерения).

См. также

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

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

Источник

Метод Global.PointsToCentimeters (Word)

Преобразует измерение из точек в сантиметры (1 сантиметр = 28,35 точек). Возвращает преобразованное измерение в виде единицы.

Синтаксис

выражение. PointsToCentimeters ( _Points_ )

Выражение Переменная, представляющая глобальный объект. Необязательный параметр.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Points Обязательный Single Измерение в точках.

Возвращаемое значение

Пример

В этом примере значение 30 точек преобразуется в соответствующее число сантиметров.

В этом примере значение переменной sngData (измерение в точках) преобразуется в сантиметры, дюймы, линии, миллиметры или пика в зависимости от значения переменной intUnit (значение от 1 до 5, указывающее результирующая единица измерения).

См. также

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

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

Источник

Application.PointsToCentimeters method (Word)

Converts a measurement from points to centimeters (1 centimeter = 28.35 points). Returns the converted measurement as a Single.

Syntax

expression. PointsToCentimeters ( _Points_ )

expression A variable that represents an Application object. Optional.

Parameters

Name Required/Optional Data type Description
Points Required Single The measurement, in points.

Return value

Example

This example converts a measurement of 30 points to the corresponding number of centimeters.

This example converts the value of the variable sngData (a measurement in points) to centimeters, inches, lines, millimeters, or picas, depending on the value of the variable intUnit (a value from 1 through 5 that indicates the resulting unit of measurement).

See also

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.

Источник

VBA: Convert centimeters, inches & pixels to points

It is frustrating that Excel, PowerPoint and Word work natively using a measurement known as points. However, measurements within the standard application menus are set in centimeters or inches. This can be seen when setting the position and size of a shape in PowerPoint through the standard menus.

Measurements in standard menus are in Centimeters

Yet, when using a macro to retrieve the position of that same shape, it displays the value in points.

Measurements for VBA are in Points

Below is the PowerPoint VBA Code to show the dimensions of the active shape:

Whether the displayed measurements are in centimeters or inches is set through the Control Panel for PowerPoint. For Excel, the default is also set through the Control panel, but this can be changed to be non-default within the Excel options. File -> Options -> Advanced -> Display -> Ruler Units.

Converting from Inches or Centimeters to Points

Converting from inches or centimeters into points is reasonably straightforward, as there are 72 points to an inch or 28.35 points to a centimeter (rounded to 2 decimal places). Microsoft has provided two useful VBA function to make this conversion

Convert from Inches to Points

Convert from Centimeters to Points

Convert from Points to Centimeters

Convert from Points to Inches

Converting from Points to Pixels

What about Pixels? Whilst Pixels may seem to be an understandable unit of measure for the purposes of controlling positions of objects, it’s not as useful as you might expect.

The number of pixels will depend on a variety of factors, such as screen resolution used for each monitor. However, if you are desperate to convert points to pixels the following VBA code could be used.

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:

Источник

ща смотрю свою функцию по определению координат указанной ячейки в Excel. Оказалось что она все пиксели правильно подсчитывала, а проблема была не с ней, а UserForm.Top
Смешно, если б не было так грустно, специально сейчас проверил, на своем мониторе при разрешении 640*800 верхний край UserForm исчезает уже при значении Top=448(таскбар убран)…

Теперь пытаюсь понять, в каких же единицах задается этот самый UserForm.Top???
Может кто-нибудь в курсе этого прикола, а главное, как у Вас там с этим свойством?

21 ответ

258

17 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Цитата:

Originally posted by SergeySV
640*800

Конечно же — 600*800 (640 это я о чем то другом думал)

Но вопрос остается, кто-нибудь в курсе в каких координатах задается положение UserForm в Excel…?

258

17 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Цитата:

Originally posted by SergeySV

Но вопрос остается, кто-нибудь в курсе в каких координатах задается положение UserForm в Excel…?

???

267

17 декабря 2003 года

Cutty Sark

1.2K / / 17.10.2002

Цитата:

Originally posted by SergeySV

???

У меня при 1024х768 правый нижний угол экрана получается при 767х575.

Эта хрень, очевидно, меряется в микрософтах. 1000 микрософтов = 1 миллисофт, 1000 миллисофтов = 1 софт. Эталонный экземпляр 1 софта хранится в Парижской Палате Мер и Софтов. В пиксели переводится по формуле 4 пикселя = 3 микрософта.
Интересна историческая подоплека появления такой единицы. Когда выбирался размер пикселя, ответственный за это Уильям Ворота (Сиэтл, США), выбрал пиксель равным 1/1024 ширины своей задницы. Когда дело дошло до выбора единицы измерений для свойств .Top и .Left у формы в Экселе, Уильям вспомнил о той своей концепции, и принял за единицу 1/1024 ширины своего зада. Однако он забыл учесть, что ввиду большого коммерческого успеха предыдущих продуктов его фирмы задница Уильяма стала шире на 33.3%. Так получилась новая единица измерения — микрософт.

258

17 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Одназначно, это один из лучших ответов :) :D :D :angel:

258

17 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Ну ладно, ничего с этим не поделаешь, теперь вооруженный этими знаниями подкорректирую свою функцию, чтобы она выдавала координаты в пикселях и в микрософтах на выбор пользователя и выложу в Исходниках.

P.S. Cutty Sark, а ты мою просьбу не пропустил на счет исправления Си/С++ на VBA…. а то не хочется пугать народ :roll:

258

17 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Cutty Sark: ты будешь смеяться, но оказывается высота строк задается в тех же микрософтах — 12,75 микрософтов = 17 пикселям, т.е. тот же 1,33 коэфф.

я тут даже подумал, может они в миллиметрах, решили задавать, но опять не дотягивает, там от силы 5 милл.

258

17 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Нашел наконец эту загадачную микрософсткую величину, пойнтом ее кличат:

point: Unit of measure referring to the height of a printed character. A point equals 1/72 of an inch, or approximately 1/28 of a centimeter.)

о как, интересно токо какой дюйм они имеют ввиду, логический, физический или еще какой

265

17 декабря 2003 года

Gauss

975 / / 20.02.2000

Цитата:

Originally posted by SergeySV
Нашел наконец эту загадачную микрософсткую величину, пойнтом ее кличат:

point: Unit of measure referring to the height of a printed character. A point equals 1/72 of an inch, or approximately 1/28 of a centimeter.)

о как, интересно токо какой дюйм они имеют ввиду, логический, физический или еще какой

point-это точка, а дюйм это приблизительно 2,25 сантиметра

258

18 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Цитата:

Originally posted by Gauss
point-это точка, а дюйм это приблизительно 2,25 сантиметра

2,24 если быть точным, но это нормальный дюйм, физический, а главное, меня это не греет, мне то нужно в пикселях. Через API я могу получить кол-во пикселей в логическом дюйме, но он не приблизительно в 1,5 раз больше физического дюйма, т.е. точно не известно во скоко раз больше лог. дюйм реального (наверное потому что это никому не надо). Поэтому если они имели ввиду физический дюйм, тогда надо перевести скоко это составит в лог. дюймах, потом узнать скоко пикселей в лог. дюйме, а потом уже расчитать скоко пикселей уместилось…. если половина данных из необходимых известна как — приблизительно, то проще наверное просто найти конечный коэффицент и его использовать, тем более, что судя по всему, разницы между разрешениями 800*600 и 1024*768 нету, а на счет других можно и положить… :(

258

18 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

О, нашел кажись:

1 point == 1 pixel/72 * dpi,

dpi — это то что в свойствах экрана называется кол-во точек в дюйме, обычно равняется 96 (на больших мониторах это значение больше),
так что произведя эти вычисления мы как раз и получим свои 1,333

267

18 декабря 2003 года

Cutty Sark

1.2K / / 17.10.2002

Цитата:

Originally posted by SergeySV
О, нашел кажись:

1 point == 1 pixel/72 * dpi,

dpi — это то что в свойствах экрана называется кол-во точек в дюйме, обычно равняется 96 (на больших мониторах это значение больше),
так что произведя эти вычисления мы как раз и получим свои 1,333

Парни, дюйм 2.54см, а не 2.24.(см. сюда)
Ну да ладно… А я вчера подумал про эти точки, в Корел Дро есть переключатель единицы измерения — пиксель-точка. Готов понять, когда эти точки применяются для того, что на печать вылезает. Но зачем формы к ним привязывать? Загадка природы…

258

18 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Цитата:

Originally posted by Cutty Sark

Парни, дюйм 2.54см, а не 2.24.(см. сюда)
Ну да ладно… А я вчера подумал про эти точки, в Корел Дро есть переключатель единицы измерения — пиксель-точка. Готов понять, когда эти точки применяются для того, что на печать вылезает. Но зачем формы к ним привязывать? Загадка природы…

Каюсь, запамятовал, конечно 2,54

На счет выбора единици измерений, points это еще не конец спектакля — в том же Access разработчикам очень полюбились твипы (Твип — это 1/1440 дюйма)
Вообщем, больше единиц измерений, хороших и разных, даешь….. наверное такой плакат висит в комнате у программистов майкрософта

Ну ладно, с этим более менее понятно, но борьба продолжается, вопрос: А в чем измеряют ШИРИНУ столбцов Excel??? это что, те же points, а почему величины другие, там что dpi по гориз. и верт. разные что-ли

267

18 декабря 2003 года

Cutty Sark

1.2K / / 17.10.2002

Цитата:

Originally posted by SergeySV
Ну ладно, с этим более менее понятно, но борьба продолжается, вопрос: А в чем измеряют ШИРИНУ столбцов Excel??? это что, те же points, а почему величины другие, там что dpi по гориз. и верт. разные что-ли

Про ширину я знаю — это среднее количество символов типа 0-9 (например, восьмёрок), помещающееся в ячейке. Шрифт берётся тот, который в меню Сервис/Параметры… вкладка «Общие».
Неужели, Серёж, ты сам не догадался? Это же так естественно… :)

258

18 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Цитата:

Originally posted by Cutty Sark

Про ширину я знаю — это среднее количество символов типа 0-9 (например, восьмёрок), помещающееся в ячейке. Шрифт берётся тот, который в меню Сервис/Параметры… вкладка «Общие».
Неужели, Серёж, ты сам не догадался? Это же так естественно… :)

Да читал когда-то краем глаза, но уже очень не хотелось верить, что такой геморой с переводом в пиксели будет, это ведь тогда надо брать шрифт, определять его параметры, потом вычислять…. йо хо хо и бутылка рома

265

18 декабря 2003 года

Gauss

975 / / 20.02.2000

Цитата:

Originally posted by Cutty Sark

Парни, дюйм 2.54см, а не 2.24.(см. сюда)

Я окончательно уехала! Твоя крыша. :)

258

22 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Наконец-то домучил вычисление ширины и высоты столбцов и строк в Excel.
Полученный модуль — mdlSysMetrics.zip, выложил в Исходниках->Офисные приложения.

В нем реализованы следующие осн. функции:
1. WidthExcColToPixel — переводит ширину столб. Excel в пиксели.
1. PointToPixel — перевод points в пиксели.(испол. для получения высоты строки Excel в пикселях)
2. PixelToPoint — перевод пикселей в points.
3. MetricsFont — возвращает хар-ки указанного шрифта: ср. ширину символа, макс. ширину символа, высоту символа, величину межстрочного интервала.

P.S. Cutty Sark: я думал это у меня Opera глючит, а оказалось что и через IE такая же фигня, добавляешь файл в Исходники указывая язык VBA, а получается С/С++. Не, я понимаю, что язык Си крутой, но что до такой степени… , наверное прям на ходу все конвертируется в него :-)
Обратишь там внимание кого следует…, ок!?

459

23 декабря 2003 года

gacol

273 / / 12.02.2003

Цитата:

Originally posted by SergeySV
Наконец-то домучил вычисление ширины и высоты столбцов и строк в Excel.
Полученный модуль — mdlSysMetrics.zip, выложил в Исходниках->Офисные приложения.

В нем реализованы следующие осн. функции:
1. WidthExcColToPixel — переводит ширину столб. Excel в пиксели.
1. PointToPixel — перевод points в пиксели.(испол. для получения высоты строки Excel в пикселях)
2. PixelToPoint — перевод пикселей в points.
3. MetricsFont — возвращает хар-ки указанного шрифта: ср. ширину символа, макс. ширину символа, высоту символа, величину межстрочного интервала.

Возможно я не правильно понял твои проблемы, но!
В принципе в ВБА Экселя есть куча функций PointTo… и обратно, например PointsToScreenPixelsX и PointsToScreenPixelsY
А поинты пошли из ВизиВиг (что вижу, то и печатаю)
В них, в частности, задаются размеры шрифтов.

258

23 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Цитата:

Originally posted by gacol

Возможно я не правильно понял твои проблемы, но!
В принципе в ВБА Экселя есть куча функций PointTo… и обратно, например PointsToScreenPixelsX и PointsToScreenPixelsY
А поинты пошли из ВизиВиг (что вижу, то и печатаю)
В них, в частности, задаются размеры шрифтов.

Ну главная проблема была по переводы ширины столбца Excel, которая опр. в кол-ве символов, кроме того определения ширины символов шрифта удобно и для других целей (для опр. длины строки есть конечно другая API функция более удобная, чем ср. ширина символов…, может я допишу ее к этому модулю)
А на счет PointsToScreenPixelsX, это конечно замечательно, но чтото я с ними не разобрался, то ли они другие Points имеют в виду, но у меня то была задача перевести высоту строк Excel (именно их Points), а PointsToScreenPixelsX(Y) возвращают какие-то другие значения, например: высота в Excel строки = 13.5 это соотв. 18 пикселям, а PointsToScreenPixelsY возвращает 145, так что не ничего не понял и написал свои функции

258

23 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

То что я написал не является конечно истиной в последней инстанции, так что если у кого-то есть какие-то замечания, пожелания к функциям — высказывайтесь,… вместе мы исправим все неточности и ошибки и надеюсь дойдем до истины.

P.S. дописал для этого модуля функцию по определению длины/высоты заданной строки опр. шрифта, после всестороннего обсуждения можно будет ее добавить в итоговый модуль

258

23 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Продолжая разбираться с этими ширинами и высотами допетрил наконец до замысла программистов microsoft на счет ширины столбца:
у объекта Range есть такие свойства:
.Height и RowHeight и оба они возвращают одинаковую высоту в points,…. дойдя до них, я автоматом подумал что с .Width и .ColumnWidth такая же фигня, и стал писать для них отдельную функцию
Однако с шириной все немного хитрее: .Width возвращает ширину в их дурацких кол-вах символов шрифта по умолч. умещающихся в ячейке, а вот .ColumnWidth возвращает эту же ширину но уже в их любимых points…. так что в принципе без WidthExcColToPixel и MetricsFont можно и обойтись (хотя все равно прикольно)

258

23 декабря 2003 года

SergeySV

1.5K / / 19.03.2003

Цитата:

Originally posted by SergeySV
Продолжая разбираться с этими ширинами и высотами допетрил наконец до замысла программистов microsoft на счет ширины столбца:
у объекта Range есть такие свойства:
.Height и RowHeight и оба они возвращают одинаковую высоту в points,…. дойдя до них, я автоматом подумал что с .Width и .ColumnWidth такая же фигня, и стал писать для них отдельную функцию
Однако с шириной все немного хитрее: .Width возвращает ширину в их дурацких кол-вах символов шрифта по умолч. умещающихся в ячейке, а вот .ColumnWidth возвращает эту же ширину но уже в их любимых points…. так что в принципе без WidthExcColToPixel и MetricsFont можно и обойтись (хотя все равно прикольно)

Блин, перлепутал, наоборот: .Width — в points, а .ColumnWidth в кол-ве символов

Понравилась статья? Поделить с друзьями:
  • Excel vba for to ubound
  • Excel vba pivottable all
  • Excel vba for textbox
  • Excel vba pivotcache refresh
  • Excel vba listing files