
利用VBA在Excel中播放MP3音樂
在VBA中通過調(diào)用API函數(shù)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
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中調(diào)用上述代碼。
播放MP3:MMPlay (Mp3File)
停止播放:MMStop (Mp3File)
其中Mp3File為包含路徑的MP3文件名。
下面是一個(gè)簡(jiǎn)單的示例,在工作表“Sheet1”中有兩個(gè)按鈕,一個(gè)是“打開并播放MP3文件”,另一個(gè)是“停止播放”。單擊“打開并播放MP3文件”按鈕可以在“打開”對(duì)話框中選擇一個(gè)MP3音樂文件并播放。

