首页officeexcel正文

利用VBA在Excel中播放MP3音乐

强国说学习2023-04-2070利用VBAExcel播放MP3音乐

在VBA中通过调用API函数mcisendstring,可以播放MP3格式的音乐。下面是VBA代码,我们可以将它放入模块中,方法是在VBA编辑器中单击菜单“插入→模块”,在代码窗口中输入下列代码。

Option ExplicitPublic Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As LongPublic Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal cchBuffer As Long) As Long

Private Function ConvShortFilename(ByVal strLongPath$) As StringDim strShortPath$If InStr(1, strLongPath, " ") ThenstrShortPath = String(LenB(strLongPath), Chr(0))GetShortPathName strLongPath, strShortPath, Len(strShortPath)ConvShortFilename = Left(strShortPath, InStr(1, strShortPath, Chr(0)) - 1)ElseConvShortFilename = strLongPathEnd IfEnd Function

文章的内容来源于网络,由强国说-WPS之家(wps.qiangguoshuo.com)收集,希望能为您提供帮助。

Public Sub MMPlay(ByRef FileName As String)FileName = ConvShortFilename(FileName)mciSendString "close " & FileName, vbNullString, 0, 0mciSendString "open " & FileName, vbNullString, 0, 0mciSendString "play " & FileName, vbNullString, 0, 0End Sub

Public Sub MMStop(ByRef FileName As String)FileName = ConvShortFilename(FileName)mciSendString "stop " & FileName, vbNullString, 0, 0mciSendString "close " & FileName, vbNullString, 0, 0End Sub

然后,可以在VBA中调用上述代码。

播放MP3:MMPlay (Mp3File)

停止播放:MMStop (Mp3File)

其中Mp3File为包含路径的MP3文件名。

下面是一个简单的示例,在工作表“Sheet1”中有两个按钮,一个是“打开并播放MP3文件”,另一个是“停止播放”。单击“打开并播放MP3文件”按钮可以在“打开”对话框中选择一个MP3音乐文件并播放。

如想转载该文章请注明出处:强国说学习-qiangguoshuo.com
强国说学习

转载声明:本站发布文章及版权归原作者所有,转载本站文章请注明文章来源!

本文链接:https://www.qiangguoshuo.com/excel/70473.html