简体   繁体   中英

Excel VBA - MkDir returns “Path not Found” when using variable

So here's the relevant snippet of my code (COPSFolder is a constant defined elsewhere):

Sub CreateReport(ByRef InfoArray() As String)

Dim BlankReport As Workbook
Dim ReportSheet As Worksheet

Dim ProjFolder As String

ProjFolder = COPSFolder & "InProgress\" & InfoArray(3) 
If Not Dir(ProjFolder, vbDirectory) = vbNullString Then
   Debug.Print ProjFolder
   MkDir ProjFolder <-----ERROR 76 HAPPENS HERE
End If

On the line indicated, ProjFolder & "InProgress\\" is an existing directory. I'm trying to create a folder within it based on a value in an array of strings.

Here's what boggles me. If I replace "InfoArray(3)" with a string (ex. "12345") it works fine, but trying to use an element in the array will throw the error. The array is defined as a string everywhere it is referenced, and there are no type mismatches elsewhere in the Module.

edit: Public Const COPSFolder As String = "\\\\ktch163\\COPS\\"

edit2: here's another weird thing - if I replace InfoArray(3) with Str(InfoArray(3)) it seems towork. What I don't get is that the value of InfoArray(3) is already defined as a string. Also, it adds a space in front of the value. I can use Right(Str(InfoArray(3)), 5) I guess, but would like to figure out what the real issue is here.

edit3: as requested, here's how InfoArray() is populated:

    Public Function GetPartInfo(ByRef TextFilePath As String) As String()
'Opens text file, returns array with each element being one line in the text file
'(Text file contents delimited by line break character)

   Dim fso As FileSystemObject: Set fso = New FileSystemObject
   Dim Info As Variant
   Dim txtstream As Object
   Dim item as Variant

   Debug.Print TextFilePath

   Set txtstream = fso.OpenTextFile(TextFilePath, ForReading, False)

   GetPartInfo = Split(txtstream.ReadAll, Chr(10))

   For Each item In GetPartInfo
      item = Trim(item)
   Next
    End Function

Later on in the code - InfoArray = GetPartInfo(File.Path) . (File.Path works fine, no errors when running GetPartInfo

The problem is that you are splitting using Chr(10) This is not removing the spaces. And hence when you are calling ProjFolder = COPSFolder & "InProgress\\" & InfoArray(3) , you have spaces in InfoArray(3)

You have 3 options

  1. When you are creating the array, remove the spaces there OR

  2. When you are assigning InfoArray = GetPartInfo(File.Path) , remove the spaces there OR

  3. Change the line ProjFolder = COPSFolder & "InProgress\\" & InfoArray(3) to ProjFolder = COPSFolder & "InProgress\\" & Trim(InfoArray(3))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM