Прескочи на основното съдържание

Как винаги да държите диаграма в изглед, когато превъртате в Excel?

Автор: Слънце Последна промяна: 2020-07-22

Ако има вмъкната диаграма в лист, докато превъртате листа надолу, за да видите данните, диаграмата не може да се види едновременно с показаната по-долу екранна снимка, което трябва да е неприятно. В тази статия въвеждам код на VBA, за да поддържате диаграма винаги пред очите, дори когато превъртате листа надолу или нагоре.

doc поддържайте диаграмата в изглед 1
doc стрелка надолу
doc поддържайте диаграмата в изглед 2

Винаги дръжте графика пред очите си


стрелка син десен балон Винаги дръжте графика пред очите си

За да запазите диаграма в изглед, докато превъртате листа, можете да приложите кода на VBA по-долу, за да го разрешите.

1. Щракнете с десния бутон върху раздела на листа, който искате да запазите диаграмата видима, и щракнете Преглед на кода формирайте контекстното меню. Вижте екранна снимка:
doc поддържайте диаграмата в изглед 3

2. В пукането Microsoft Visual Basic за приложения прозорец, поставете кода по-долу в празния скрипт.

VBA: Дръжте диаграмата винаги в изглед

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'UpdatebyExtendoffice20161111
    Dim CPos As Double
    Application.ScreenUpdating = False
    CPos = ActiveWindow.ScrollRow * ActiveCell.RowHeight
    ActiveSheet.ChartObjects("Chart 2").Activate
    ActiveSheet.Shapes("Chart 2").Top = CPos
    ActiveWindow.Visible = False
    Application.ScreenUpdating = True
End Sub

doc поддържайте диаграмата в изглед 5

3. Запазете и затворете диалоговия прозорец, след което диаграмата ще се премести надолу или нагоре, когато щракнете върху която и да е клетка.
doc поддържайте диаграмата в изглед 6

Забележки:

(1) В кода на VBA Диаграма 2 е името на диаграмата, което искате да запазите в изгледа си, можете да го промените според нуждите си.

(2) Този VBA не може винаги да държи група диаграми в изглед.

Най-добрите инструменти за продуктивност в офиса

🤖 Kutools AI помощник: Революционизирайте анализа на данни въз основа на: Интелигентно изпълнение   |  Генериране на код  |  Създаване на персонализирани формули  |  Анализирайте данни и генерирайте диаграми  |  Извикване на функциите на Kutools...
Популярни функции: Намерете, маркирайте или идентифицирайте дубликати   |  Изтриване на празни редове   |  Комбинирайте колони или клетки без загуба на данни   |   Кръг без формула ...
Супер търсене: VLookup с множество критерии    VLookup с множество стойности  |   VLookup в няколко листа   |   Размито търсене ....
Разширен падащ списък: Бързо създаване на падащ списък   |  Зависим падащ списък   |  Падащ списък с множество избори ....
Мениджър на колони: Добавете конкретен брой колони  |  Преместване на колони  |  Превключване на състоянието на видимост на скритите колони  |  Сравнете диапазони и колони ...
Препоръчани функции: Мрежов фокус   |  Изглед на дизайна   |   Голям формула бар    Мениджър на работни книги и листове   |  Библиотека с ресурси (Автоматичен текст)   |  Избор на дата   |  Комбинирайте работни листове   |  Шифроване/декриптиране на клетки    Изпращайте имейли по списък   |  Супер филтър   |   Специален филтър (филтър получер/курсив/зачертано...) ...
Топ 15 комплекта инструменти12 Текст Инструменти (добавяне на текст, Премахване на символи, ...)   |   50 + Графика Видове (диаграма на Гант, ...)   |   40+ Практичен формули (Изчислете възрастта въз основа на рождения ден, ...)   |   19 вмъкване Инструменти (Въведете QR код, Вмъкване на картина от пътя, ...)   |   12 Конверсия Инструменти (Числа към думи, Валутен обмен, ...)   |   7 Обединяване и разделяне Инструменти (Разширено комбиниране на редове, Разделени клетки, ...)   |   ... и още

Усъвършенствайте уменията си за Excel с Kutools за Excel и изпитайте ефективност, както никога досега. Kutools за Excel предлага над 300 разширени функции за повишаване на производителността и спестяване на време.  Щракнете тук, за да получите функцията, от която се нуждаете най-много...

Описание


Раздел Office Внася интерфейс с раздели в Office и прави работата ви много по-лесна

  • Разрешете редактиране и четене с раздели в Word, Excel, PowerPoint, Publisher, Access, Visio и Project.
  • Отваряйте и създавайте множество документи в нови раздели на един и същ прозорец, а не в нови прозорци.
  • Увеличава вашата производителност с 50% и намалява стотици кликвания на мишката за вас всеки ден!
Comments (15)
Rated 4.75 out of 5 · 2 ratings
This comment was minimized by the moderator on the site
A mí me pasa que la siguiente vez que abro el archivo, el script ya no funciona. Tengo que copiarlo, borrarlo, cerrar el archivo tras guardarlo, volver a abrir el archivo y volver a pegar el script en VBA. ¿Alguna solución?
Rated 4.5 out of 5
This comment was minimized by the moderator on the site
Hi, save the workbook as excel macro enable workbook, the vba will be work when open next time.https://cdn.extendoffice.com/images/stories/comments/sun-comment/doc-macro-enable.png
This comment was minimized by the moderator on the site
I encountered a problem with unselecting the cell and needed two charts, So I made some changes and it seems to work now.
To use it put the right Chart Name.
*Note: This one is for two charts


Private Sub worksheet_selectionchange(ByVal target As Range)
Dim chartposition As Double

chartposition = ActiveWindow.ScrollRow * ActiveCell.RowHeight
ActiveSheet.Shapes("Chart 2").Top = chartposition

ActiveSheet.ChartObjects("Chart 3").Top = chartposition + 250

End Sub
This comment was minimized by the moderator on the site
Can any one assist. when i follow theses steps


Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'UpdatebyExtendoffice20161111
Dim CPos As Double
Application.ScreenUpdating = False
CPos = ActiveWindow.ScrollRow * ActiveCell.RowHeight
ActiveSheet.ChartObjects("Chart 2").Activate
ActiveSheet.Shapes("Chart 2").Top = CPos
ActiveWindow.Visible = False
Application.ScreenUpdating = True
End Sub


i get the following err

Run-Time error '-2147024809 (80070057)':
The item with the specified name was not found

when i debug
ActiveSheet.ChartObjects("Chart 2").Activate
This comment was minimized by the moderator on the site
Hi, Christo, you need to change the chart name "Chart 2" to your chart really name in the script. You can click at the chart and see its name in the name box. See screenshot:
https://www.extendoffice.com/images/stories/comments/sun-comment/do_chart_name.png
This comment was minimized by the moderator on the site
yes thanks. after a made the question i realised my chart name was wrong
thanks

ps.
do you perhaps know how i can make the chart kept in view as i scroll without clicking where it must follow
This comment was minimized by the moderator on the site
can I use Kutools to automatically use that VBA for my charts??
This comment was minimized by the moderator on the site
Sorry, Wangnuli, Kutools has not support this so far.
This comment was minimized by the moderator on the site
Hola muchas gracias por el código, utilizando este código ¿Hay alguna manera de limitar qué tan alto en la hoja se reubicará el gráfico? por ejemplo, no quiero que se coloque encima de la fila 9. Ayuda por favor.
Rated 5 out of 5
This comment was minimized by the moderator on the site
Is there a way to limit how high up on the sheet the chart will relocate to? I don't want it to affix above row 8
This comment was minimized by the moderator on the site
Is there a similar formula that can be built for Google Sheets?
This comment was minimized by the moderator on the site
This macro did exactly what I wanted. However it created another problem that I wondered if you might have a solution to.

While this macro is active I cannot select cells for other purposes such as formatting or merging them. Click and drag, shift nor ctrl work to select a group of cells. I can only select the one cell I clicked on. I frequently want to change formatting (background, fill down a formula, etc.) The only way I have been able to do this is to delete the macro, save, make my formatting changes, paste the macro back in and save.

Is there a simpler way to do this? Perhaps:

1. (preferred) A simple keystroke that would temporarily disable the macro and then re-enable it.

2. Some code added to the macro to allow selection of a group of cells.

Dennis
This comment was minimized by the moderator on the site
This was good but I wish there was a way that it would just move with the scroll wheel, like heading lines. Also if I want to select a cell it takes two clicks. The first click moves the chart but also selects the chart so I have to click again to select the cell.
This comment was minimized by the moderator on the site
I added "activecell.select" on the last line of this code and it fixed the double clicking issue. It will automatically select the last active cell, which will be the one you clicked on to move the chart. Hope this helps.
This comment was minimized by the moderator on the site
THIS IS WHAT I NEEDED! GOLDEN!
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations