2014-12-24 82 views
0

我必須將整個目錄結構(成千上萬的目錄和文件)從Mac移動到PC,但現在在PC上出於某種原因,某些文件夾名稱上有一個字符值的二進制零結束(有一些在中間)。我需要清理它,因爲它會崩潰試圖讀取這些目錄的宏。
我已經嘗試了使用Replace函數(作爲遍歷目錄樹的更大程序的一部分)的vba-word宏中的以下代碼,但Replace函數似乎沒有捕獲到chr(0)。從字符串中刪除二進制零

Set current_folder = fso.GetFolder(source_folder.Path) 
current_folder_name = current_folder.Name 
cleaned_folder_name = Replace(current_folder_name, Chr(0), " ") 
Selection.TypeText "Old directory name: " & current_folder_name 
Selection.TypeParagraph 
Selection.TypeText "New directory name: " & cleaned_folder_name 
Selection.TypeParagraph 
If current_folder_name <> cleaned_folder_name Then 
    current_folder.Name = cleaned_folder_name 
End If 

我也試過: cleaned_folder_name =替換(current_folder_name,CHR(0), 「」,1,-1,vbBinaryCompare)

如何,我可以得到替換功能,以取代二進制0在一個空白字符串中。

還是有人知道一個不同的方法來清理這些目錄和文件名將工作。

感謝, 哈利

+0

首先,您是否希望將'Chr(0)'替換爲'Space'或'Nothing'?因爲你現在在你的'replace()'函數中有一個空格。 – Chrismas007

+0

我可能會在我的程序中進行測試,如果Chr(0)在結束時沒有其他空間。我會嘗試你的解決方案並回復你。謝謝。 –

回答

1

這應做到:

Dim OldFolderName As String, NewFolderName As String 

OldFolderName = source_folder.Path 
If InStr(OldFolderName, Chr(0)) > 0 Then 
    'NewFolderName = Application.Clean(OldFolderName) 'Works on some versions 
    NewFolderName = Application.WorksheetFunction.Clean(OldFolderName) 'By Gene Skuratovsky 
    Name OldFolderName As NewFolderName 
End If 

EDIT2:可能最好使用Clean()方法。

+0

我不認爲這會奏效。清空文件夾名=替換(current_folder_name,Chr(0),「」) 總是在我的代碼中執行,但是Chr(0)永遠不會被空間替換。 –

+0

你確定這個字符是'Chr(0)'嗎? – Chrismas007

+0

在我的原始答案中加入了一些關於'「\ 0」的內容。 – Chrismas007

0

您可以編寫自定義循環功能,以確定您有問題什麼字符:

OldFolderName = source_folder.Path 
For x = 0 To 255 
    If InStr(OldFolderName, Chr(x)) > 0 Then 
     MsgBox "Chr(" & x & ") is found at position " & InStr(OldFolderName, Chr(x)) 
    EndIf 
Next x 
+0

我解決了它。它不是二進制零(當它被粘貼到一個十六進制編輯器時它變成了二進制零)。我將字符串分配給一個字節數組,發現了什麼是非法字符。然後編寫了一個宏,它將字符串數組的名稱字符串指定爲非法字符。然後將值填入空白並重新分配給字符串。謝謝。 –

1

在我的情況下更換()和InStr函數()不與人權委員會的工作(0)(可以」噸看到它不顯示任何錯誤),但這種去除可以做到的,例如是這樣的:

If Mid$(str, 1, 1) = Chr$(0) Then str = Mid$(str, 2) 
If Mid$(str, Len(str), 1) = Chr$(0) Then str = Left$(str, Len(str) - 1) 

這是從端部空除去,例如從objFile.ExtendedProperty("Dimensions")值,如「600×400?」。在Windows 10中,空值(?)在這裏被插入,但在Windows XP中沒有。