2014-10-24 3 views
5

좋아, 내가 여기에 기지가 될 수 있지만 내가 뭘하고 싶습니다 GetOpenFileName에 대한 API 호출의 넓은 (유니 코드) 버전을 사용하여 여러 파일의 목록을 반환합니다.VBA에서 GetOpenFileNameW?

이제 내가 원하는 이유는 다음과 같습니다. 여러 파일을 선택할 때 파일 이름의 총 문자 수 제한은 함수 버전에 따라 다릅니다. ANSI •
: 32K 제한 유니 코드 •
: 신속 ANSI의 32K 문자 제한을 초과 할 수 있습니다 내 네트워크에 깊이 묻혀 디렉토리에서 파일의 큰 선택을 반환 제한없이

합니다.

그래서 내가 한 것은 ANSI에서 선언 한 함수를 사용하고 모든 string 변수를 lngptr으로 바꾸는 것입니다. 그런 다음 여기에 값을 할당해야하는 곳에서 StrPtr() 함수를 사용하여 문자열 값을 변환했습니다.

지금이 함수가 선언 된 함수를 호출하는 부분에 도착하면이 함수를 호출하려고 시도하면 lReturn = GetOpenFileNameU(OpenFile)은 실제로 아무 것도 수행하지 않습니다. 오류가없고, 아무 것도 없습니다. 바로 그 행을 지나고 아무 조치도 취하지 않습니다. 내가 뭘 잘못 했니 ?? 내가 지금에 어딘지

이는 다음과 같습니다

Option Explicit 
'***NOTE: _ 
    This class object requires the following references: _ 
     <NONE> 

'Declare the windows API function for GetOpenFileNameA 
'MSDN Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646927(v=vs.85).aspx 
Public Declare PtrSafe Function GetOpenFileNameU Lib "comdlg32.dll" Alias "GetOpenFileNameW" (pOpenfilename As OPENFILENAME) As Long 

Public Const OFN_ALLOWMULTISELECT As Long = &H200 
Public Const OFN_CREATEPROMPT As Long = &H2000 
Public Const OFN_ENABLEHOOK As Long = &H20 
Public Const OFN_ENABLETEMPLATE As Long = &H40 
Public Const OFN_ENABLETEMPLATEHANDLE As Long = &H80 
Public Const OFN_EXPLORER As Long = &H80000 
Public Const OFN_EXTENSIONDIFFERENT As Long = &H400 
Public Const OFN_FILEMUSTEXIST As Long = &H1000 
Public Const OFN_HIDEREADONLY As Long = &H4 
Public Const OFN_LONGNAMES As Long = &H200000 
Public Const OFN_NOCHANGEDIR As Long = &H8 
Public Const OFN_NODEREFERENCELINKS As Long = &H100000 
Public Const OFN_NOLONGNAMES As Long = &H40000 
Public Const OFN_NONETWORKBUTTON As Long = &H20000 
Public Const OFN_NOREADONLYRETURN As Long = &H8000& '*see comments 
Public Const OFN_NOTESTFILECREATE As Long = &H10000 
Public Const OFN_NOVALIDATE As Long = &H100 
Public Const OFN_OVERWRITEPROMPT As Long = &H2 
Public Const OFN_PATHMUSTEXIST As Long = &H800 
Public Const OFN_READONLY As Long = &H1 
Public Const OFN_SHAREAWARE As Long = &H4000 
Public Const OFN_SHAREFALLTHROUGH As Long = 2 
Public Const OFN_SHAREWARN As Long = 0 
Public Const OFN_SHARENOWARN As Long = 1 
Public Const OFN_SHOWHELP As Long = &H10 
Public Const OFN_ENABLESIZING As Long = &H800000 
Public Const OFS_MAXPATHNAME As Long = 260 

'Create a custom type that matches the OPENFILENAME structure 
'MSDN reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646839(v=vs.85).aspx 
Public Type OPENFILENAME 
    lStructSize As Long 
    hwndOwner As LongPtr 
    hInstance As LongPtr 
    lpstrFilter As LongPtr 
    lpstrCustomFilter As LongPtr 
    nMaxCustFilter As Long 
    nFilterIndex As Long 
    lpstrFile As LongPtr 
    nMaxFile As Long 
    lpstrFileTitle As LongPtr 
    nMaxFileTitle As Long 
    lpstrInitialDir As LongPtr 
    lpstrTitle As LongPtr 
    flags As Long 
    nFileOffset As Integer 
    nFileExtension As Integer 
    lpstrDefExt As LongPtr 
    lCustData As Long 
    lpfnHook As LongPtr 
    lpTemplateName As LongPtr 
End Type 


'OFS_FILE_OPEN_FLAGS: 
'Can view explanation of flags here on the MSDN reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646839(v=vs.85).aspx 
Public Const OFS_FILE_OPEN_FLAGS = _ 
       OFN_EXPLORER Or _ 
       OFN_LONGNAMES Or _ 
       OFN_CREATEPROMPT Or _ 
       OFN_NODEREFERENCELINKS 

'Windows version constants 
Private Const VER_PLATFORM_WIN32_NT As Long = 2 
Private Const OSV_LENGTH As Long = 76 
Private Const OSVEX_LENGTH As Long = 88 
Public OSV_VERSION_LENGTH As Long 

Public Const WM_INITDIALOG As Long = &H110 
Private Const SW_SHOWNORMAL As Long = 1 


Public Function BrowseForFile(strTitle As String, myFilter As String, Optional initialDir As String = "") As String 
'This function allows you to browse for files and returns a string containing the files selected 

'Declare variables 
    Dim OpenFile As OPENFILENAME 
    Dim lReturn  As Long 
    Dim strFile  As String 


'Set the file type filter 
    OpenFile.lpstrFilter = StrPtr(myFilter) 

'Set the filter index. This is the order of the filters available to select from in the dialog. 1= the first in the list (and currently active) 
    OpenFile.nFilterIndex = 1 

'Set the handle to the window that owns the dialog box 
    OpenFile.hwndOwner = 0 

'lpstrFile is a pointer to a string which contains the current directory followed by list of file names selected. _ 
'Create an empty string to use as buffer, it needs to be at least 256 chars plus a terminating NULL char 
    strFile = String(257, 0) 
'Pass the buffer string to the pointer 
    OpenFile.lpstrFile = StrPtr(strFile) 

'The size of nMaxFile = the size, in characters, of the string pointed to by lpstrFile (less one NULL character at the end) 
'The size of lStructSize = The length, in bytes, of the structure. Use size of (OPENFILENAME) for this parameter. 

'BEFORE we can set the above two properties, we need to heck which version of VBA we are working with (SW uses VBA7, Office uses VBA6) _ 
The # indiicates preprocessor command, which is processed prior to compilation, which ensures that the code compiles per the correct platform 
     #If VBA7 Then 
     'When environment is VBA7, use LenB (binary compare) 
      OpenFile.nMaxFile = LenB(strFile) - 1 
      OpenFile.lStructSize = LenB(strFile) 
     #Else 
     'When environment is anything else, use Len (text compare) 
      OpenFile.nMaxFile = Len(strFile) - 1 
      OpenFile.lStructSize = Len(strFile) 
     #End If 

'This points to a string containing just the file name and extension (without path info), whereas lpstrFile contains the path info also. 
    OpenFile.lpstrFileTitle = OpenFile.lpstrFile 
'This is to lpstrFileTile what nMaxFile is to lpstrFile 
    OpenFile.nMaxFileTitle = OpenFile.nMaxFile 

    'Check if the calling procedure specified a starting directory 
     If initialDir <> "" Then OpenFile.lpstrInitialDir = StrPtr(StrConv(initialDir, vbUnicode)) 

'This will be the title of the window dialog, and is an argument that must be passed by the calling procedure 
    OpenFile.lpstrTitle = StrPtr(StrConv(strTitle, vbUnicode)) 

'Flags control how the window looks and acts. _ 
'Can view explanation of flags here on the MSDN reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646839(v=vs.85).aspx 
    OpenFile.flags = OFS_FILE_OPEN_FLAGS + OFN_ALLOWMULTISELECT 

'Call the windows API function we delcared and get the return when it completes. 
    lReturn = GetOpenFileNameU(OpenFile) 

'Check the return, if 0 then no files selected or user cancelled 
    If lReturn = 0 Then 
     BrowseForFile = "" 
    Else 
    'lpstrFile contains the current directory followed by list of file names 
     BrowseForFile = strFile 
    End If 
End Function 

답변

1

현재 문제가 당신이 257에 strFile을 설정하기 때문에 OpenFile.lStructSize = LenB(strFile)

을 것으로 보인다, 그것은 574 바이트가 포함되어 있습니다. 결과를 바탕으로 lStructSize는 파일에 정확히 맞는 경우에만 작동하므로 원래 파일을 사용해야합니다. OpenFile.lStructSize = LenB(OpenFile)

또한 strptr이 사용하는 방식대로 작동한다고 생각하지 않습니다. 문자열을 변환합니다. 포인터로,하지만 그 반대도 마찬가지입니다.

실제로 포인터가 문자열로 변환되는 함수를 작성했습니다. 불행하게도 그 길이를 전달하도록 요구, 나는

Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long) 

Function myConversion(lpstr As Long, lenStr As Integer) As String 
    Dim bStr() As Byte 
    On Error Resume Next 

    If lenStr Then 
     Dim lenBytes 
     lenBytes = (lenStr) * 2 
     ReDim bStr(0 To lenBytes - 1) As Byte 
     Call CopyMemory(bStr(0), ByVal lpstr, lenBytes) 

     Dim i 
     Dim s As String 
     For i = LBound(bStr) To UBound(bStr) Step 2 
      s = s & Chr(bStr(i)) 
     Next i 
    End If 

    myConversion = s 
End Function 
+0

하면 변경합니다 감사 포인터 자체를 얻기 위해 노력하고 문제를 많이했다! 'OpenFile.lStructSize = LenB (strFile)'에서'OpenFile.lStructSize = LenB (OpenFile) '로 변경하면 작동합니다! StrPtr에 대해 무슨 뜻인지 모르시겠습니까? 저는이 기능을 사용하여 문자열을 함수로 전달해야하는 포인터로만 변환하려고합니다. – CBRF23

+0

아, 이전 버전의 코드를 복사 한 것 같습니다. LongPtrs로 함수 인수를 나열 했으므로 문자열로 다시 변경하려고한다고 가정했습니다. – Alter