Vba excel windows media player

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

Воспроизвести видеофайл с листа, задав свойства Windows Media Player

Воспроизведите видеофайл с листа, нажав кнопку управления


стрелка синий правый пузырь Воспроизвести видеофайл с листа, задав свойства Windows Media Player

В Excel есть полезный элемент управления — Windows Media Play может помочь вам воспроизвести видеофайл, сделайте следующее:

1. Нажмите Застройщик > Вставить > Больше элементов управления, см. снимок экрана:

документ воспроизвести видео 1

2. В Больше элементов управления диалоговое окно, прокрутите и выберите Windows Media Player , затем нажмите OK кнопку, чтобы закрыть диалоговое окно, а затем перетащите мышь, чтобы нарисовать Windows Media Play объект, см. снимок экрана:

документ воспроизвести видео 2

3, Затем перейдите к Предложения диалоговое окно, нажав Застройщик > Предложения, В Предложения диалоговом окне выполните следующие действия:

(1.) В Алфавитный на вкладке, выберите вариант True из полноэкранный поле;

(2.) Скопируйте и вставьте путь к видеофайлу, который должен включать расширение файла, в URL поле.

документ воспроизвести видео 3

4. После завершения вышеуказанных настроек выйдите Режим дизайна, и указанное вами видео сейчас воспроизводится.


стрелка синий правый пузырь Воспроизведите видеофайл с листа, нажав кнопку управления

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

1. В соответствии с шагами 1-2 в методе 1 вставьте Windows Media Player элемент управления, а затем продолжайте щелкать Застройщик > Вставить > Кнопка управления чтобы вставить командную кнопку, см. снимок экрана:

документ воспроизвести видео 4

2. Затем щелкните правой кнопкой мыши кнопку Command и выберите Предложения из контекстного меню во всплывающем Предложения диалоговое окно введите текст Воспроизвести видео за Подпись поле под Алфавитный вкладку, см. снимок экрана:

документ воспроизвести видео 5

3. А затем закройте Предложения диалоговое окно, затем дважды щелкните кнопку Command, а затем скопируйте и вставьте следующий код VBA, чтобы заменить исходный код в Microsoft Visual Basic для приложений окно.

Код VBA: воспроизвести видеофайл с листа:

Private Sub CommandButton1_Click()
    Dim FName As Variant
    FName = Application.GetOpenFilename(FileFilter:="Video Files, *.mp4; *.avi; *.mpeg; *.mts", Title:="Please select a Video File", MultiSelect:=False)
    If FName <> False Then
        WindowsMediaPlayer1.Url = FName
    End If
End Sub

документ воспроизвести видео 6

Внимание: В приведенном выше коде CommandButton1 это имя командной кнопки, которое вы вставили, а WindowsMediaPlayer1 это имя проигрывателя Windows Media, которое вы вставили. И вы можете добавить другие расширения видеофайлов по мере необходимости в * .mp4; * .avi; * .mpeg; * .mts скрипты.

4. Затем сохраните и закройте окно кода и выйдите из Режим дизайнатеперь, когда вы нажимаете кнопку Command, появляется окно просмотра, напоминающее вам о выборе видеофайла, который вы хотите воспроизвести, затем нажмите Откройте кнопку, сразу будет воспроизведен конкретный видеофайл. Смотрите скриншот:

документ воспроизвести видео 7


Связанная статья:

Как вставить или вставить видео youtobe в лист Excel?


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

На вкладке Разработчик выбираем кнопку Вставить — Элементы ActiveX — Другие элементы управления (Developer — Insert — ActiveX — Other controls):

Другие элементы ActiveX

Затем в открывшемся окне находим Windows Media Player, жмём OK и рисуем его контейнер на листе, удерживая нажатой левую кнопку мыши:

Вставленный медиаплейер

Запоминаем имя вставленного компонента в левом верхнем углу (обычно это WindowsMediaPlayer1 или что-то похожее) и отжимаем кнопку Режим Конструктора (Design Mode), чтобы перевести плейер в рабочий режим.

Затем щёлкаем правой по ярлычку листа и выбираем команду Исходный текст (Source code). В открывшееся окно редактора макросов вводим следующий код:

Sub Radio()
    WindowsMediaPlayer1.Url = ActiveCell
    WindowsMediaPlayer1.Controls.Play
End Sub

Возвращаемся в Excel, выделяем ячейку с веб-ссылкой на потоковое вещание радиостанции и запускаем наш макрос через Разработчик — Макросы (Developer — Macros) или сочетанием клавиш Alt+F8. Для удобства также можно сделать отдельную кнопку запуска через Разработчик — Вставить — Кнопка (Developer — Insert — Button):

Результат

Воспроизведение медиа потока никак не мешает работе с данными на листах, созданию запросов Power Query, другим макросам и пр., т.к. происходит в фоновом процессе.

Простенько и со вкусом :)

We’ve had a few forum questions recently asking how to play audio files in Excel.

Normally I’d just use my media player for this but I can see that you might want to have an audio or video file that may explain something about your workbook. Or you could use Excel to play videos in order to do some training of staff.

The ability to do this kind of thing is there, so in this post I’m going to show you how to do it.

ActiveX Controls

You’re going to need to insert some ActiveX controls so you will need to enable the Developer tab if you haven’t already done this.

Required Controls

I’m going to use the Windows Media Player control, and a Command Button we can click to move to the next audio/video file.

To insert these, from the Developer tab, click on Insert, then More Controls. From the pop-up window, scroll down to Windows Media Player, select it and click OK.

You’ll now see that your mouse pointer has changed to a cross. Click on the sheet and drag the box to the size you want the player to be.

insert windows media player control

Using a command button will allow us to click on it and load the next audio/video file. Click Insert, click on the ActiveX Command Button, and drag it to the size and position you want.

insert command button control

Editing Control Properties

By default the name and text on the button are CommandButton1, I want to change this. First, make sure you are in Design Mode.

On the Developer tab, Design Mode mode should be colored/highlighted to indicate that you are in Design Mode. When this is the case the controls won’t carry out their usual functions.

design mode

Right click on the button and click on Properties. In the Properties window, I’ve changed the caption to ‘Next’ and changed the button’s name to ‘NextMediaFile’. We use the name in our VBA code so it’s important to have something meaningful.

Command button properties

Loading Media Files into the Player

We’ll come back to the VBA that loads the media files in a second, first I want to look at how we know what to play.

What I have done is use a specific cell, A3, to tell me the folder where the files are, and below that is a list of the files I want to play.

Please note that the filename must include the extension.

You could create a playlist in Windows Media Player and load that, and it will play everything in the playlist.

VBA

We want to click the ‘Next’ command button to load the next file so to do that we need a little VBA

Make sure you are in Design Mode, and right click the button. Click on ‘View Code’ and the VBA editor will open with an empty sub already created for you.

Note that the name of the sub is taken from the name we gave the button. Now you just need to enter the code to do the fancy stuff.

Download the VBA & Workbook

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.

vba to load next media file

How the Code Works

Each time the button is clicked the ActiveCell is moved down one row.

The code uses the ActiveCell to load the next file. If that cell is empty it goes to the start again, cell A4.

The file listed in the ActiveCell is loaded into the media player.

The code makes the assumption that there isn’t anything else on the sheet, so if you happen to have F34 selected, it won’t have anything in it. That being the case, the code will go back to the start of the media files and play the first one.

In this post, I will show you how to add additional controls such as Windows Media Player, Adobe PDF Reader and Microsoft ListView Control in Excel VBA.

So here are the steps you need to follow. First create a blank workbook.

Then click somewhere in the excel sheet and press Alt+F11 to open the VBA editor. Then click on the Insert menu and select Userform.

Once you select the Userform, a new userform will be created like this.

Also the Toolbox will appear to the side of the form as well.

Some of the controls are already in this toolbox such as Textbox, Label and ListBox etc. Now let’s look at how to add additional controls to it. To do that we need to click on the Tools menu and click on Additional Controls…

It will open the Additional Controls Window like this.

Now you can add any additional control you like. For this example let’s add Windows Media Player. Select the checkbox in front of the Windows Media Player and then click OK.

This will add Windows Media Player icon to our Toolbox like this.

Now we can add Windows Media Player to our userform.

When WMP is running in a VBA UserForm it sizes automatically based on clip size and resolution, irrespective of Width and Height properties being set programmatically. I need the video to have a fixed size. The following code does nothing:

With UserForm1.WindowsMediaPlayer1
    .URL = "C:AnyVideo.mp4"
    .Controls.Play
    .stretchToFit = True
    .Width = 500
    .Height = 300
    .Top = 0
    .Left = 0
End With

The following code does work but makes the video jumpy at the beginning — starts playing at its own size, then jumps to the new size, not a professional look.

With UserForm1.WindowsMediaPlayer1
    .URL = "C:AnyVideo.mp4"
    .Controls.Play
End With

Timer_1 = Timer + 1

Do While Timer < Timer_1
    DoEvents
Loop

With UserForm1.WindowsMediaPlayer1
    .stretchToFit = True
    .Width = 600
    .Height = 300
    .Top = 0
    .Left = 0
End With

I’ve looked around and have found nothing to explain what’s going on or to solve this. Anybody can help?

GSerg's user avatar

GSerg

75.3k17 gold badges160 silver badges340 bronze badges

asked Jun 18, 2017 at 10:14

HectorM's user avatar

0

Click on the WindowsMediaPlayer1 control and Select the custom property. You will see the «Windows Media Player Properties» Window. Uncheck the «Auto Start» option. That should resolve this problem.

Just this is enough. you no need to do any other options to be set. It won’t flicker or won’t look jumpy etc.

You can now size the WindowsMediaPlayer1 control based on whatever the size you want in the design mode itself. If you still want, you can also do the same through code as well. It should work as you expect, after you uncheck the above option.

answered Jun 18, 2017 at 13:46

Karpak's user avatar

KarpakKarpak

1,9171 gold badge15 silver badges16 bronze badges

Понравилась статья? Поделить с друзьями:
  • Vba excel workbook методы
  • Vba excel union примеры
  • Vba excel автоподбор высоты строк
  • Vba excel union range
  • Vba excel workbook protect