[Avançado] Ler o parâmetro da linha de comando pelo VBA

Se você precisa ler os parâmetros que foram passados na linha de comando ao abrir a sua planilha, vou demonstrar aqui como isso pode ser feito em poucas etapas.

Exemplo:

Em uma planilha foi incluído este código demonstrado mais abaixo, e a chamada foi feita a partir do Workbook_Open:

Option Explicit

Private Sub Workbook_Open()
  MsgBox GetCommandLine
End Sub

Chamando a planilha utilizando a seguinte linha de comando:

excel.exe E:\Dados\Desktop\temp\Pasta1.xlsm /ok

Temos o seguinte resultado ao abrir a planilha:

Com isso é possível tratar os parâmetros que foram passados através do resultado da função GetCommandLine().

O código abaixo funciona tanto em Windows 32bit quanto em Windows 64bit:

#If Win64 Then
Private Declare PtrSafe Function GetCommandLineL Lib "kernel32" _
    Alias "GetCommandLineA" () As LongPtr
Private Declare PtrSafe Function lstrcpyL Lib "kernel32" _
    Alias "lstrcpyA" (ByVal lpString1 As String, ByVal lpString2 As LongPtr) As Long
Private Declare PtrSafe Function lstrlenL Lib "kernel32" _
    Alias "lstrlenA" (ByVal lpString As LongPtr) As Long
#Else
Private Declare Function GetCommandLineL Lib "kernel32" _
    Alias "GetCommandLineA" () As Long
Private Declare Function lstrcpyL Lib "kernel32" _
    Alias "lstrcpyA" (ByVal lpString1 As String, ByVal lpString2 As Long) As Long
Private Declare Function lstrlenL Lib "kernel32" _
    Alias "lstrlenA" (ByVal lpString As Long) As Long
#End If

Function GetCommandLine() As String
  Dim strReturn As String
  #If Win64 Then
  Dim lngPtr As LongPtr
  #Else
  Dim lngPtr As Long
  #End If
  Dim StringLength As Long
  'Get the pointer to the commandline string
  lngPtr = GetCommandLineL
  'get the length of the string (not including the terminating null character):
  StringLength = lstrlenL(lngPtr)
  'initialize our string so it has enough characters including the null character:
  strReturn = String$(StringLength + 1, 0)
  'copy the string we have a pointer to into our new string:
  lstrcpyL strReturn, lngPtr
  'now strip off the null character at the end:
  GetCommandLine = Left$(strReturn, StringLength)
End Function

 

Caso precise de ajuda profissional para implementar este código ou então para automatizar a sua planilha, me envie uma mensagem através do formulário de contato que responderei em breve, se preferir, pode me enviar um e-mail através do endereço [email protected].

 

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *