Home > Net >  How to play a wave file Excel/Developer/Visual BASIC?
How to play a wave file Excel/Developer/Visual BASIC?

Time:11-25

The problem has been narrowed down to one line. It is an issue between absolute and relative path.

This line works: PlayWavFile "c:\TransmissionFile\AWNP.wav", False

I prefer something like this but it does not work: PlayWavFile "AWNP.wav", False

I have the wave file in both the C drive and in the same folder as the program. So for the program folder to be portable, I would like to use the relative path. How do I do that? What is wrong?

CodePudding user response:

Try this:

Dim CurrentFolder As String
CurrentFolder = ThisWorkbook.Path
PlayWavFile CurrentFolder & Application.PathSeparator & "AWNP.wav", False

CodePudding user response:

Your question leaves a few open questions. However, taking a best guess approach, I think this is what you're aiming to do:

Option Explicit

' assuming this is the Lib declaration:
Public Declare Function sndPlaySound Lib "winmm.dll" _
Alias "sndPlaySoundA" (ByVal lpszSoundName As String, _
ByVal uFlags As Long) As Long

' and assuming this is the sub format you're using to call (as declared) sndPlaySound
Sub PlayWavFile(WavFileName As String, Wait As Boolean)
    
    ' Set path based on this workbook's folder location
    Dim stFilePath$: stFilePath = ThisWorkbook.Path & "\" & WavFileName

    ' If file is missing, try root of C drive
    If Dir(stFilePath) = "" Then
        stFilePath = "C:\" & WavFileName
        
        ' Not here either: report and end
        If Dir(stFilePath) = "" Then
            MsgBox WavFileName & " not found"
            Exit Sub
        End If
    End If

    ' Play the sound (with/without wait)
    If Wait Then
        sndPlaySound stFilePath, 0
    Else
        sndPlaySound stFilePath, 1
    End If
End Sub
  • Related