MS Access VBA路径拼接末尾加反斜杠失效问题求助
Hey there, let's work through this path issue in your Access VBA code. First off, let's rule out the hyphen in your SKU—Windows fully supports hyphens in file/folder names, so that's definitely not causing the problem. The issue is almost certainly tied to how you're manually adding the trailing backslash, or possibly hidden invalid characters in your Fnumber or Fname variables.
Here are actionable steps to fix this:
1. Clean Up Your Variables First
It's possible that Fnumber or Fname (your SKU) has leading/trailing spaces or invisible characters that break the path. Start by trimming whitespace and removing any characters that are actually invalid for Windows paths (hyphens are fine, but things like colons, slashes, or question marks aren't):
Fnumber = Trim(Me.FolderNumber) Fname = Trim([SKU]) ' Remove invalid path characters (keep hyphens!) Fname = Replace(Replace(Replace(Replace(Fname, "/", ""), "\", ""), ":", ""), "?", "") Fname = Replace(Replace(Replace(Fname, "*", ""), """", ""), "<>", "")
2. Use FileSystemObject.BuildPath for Reliable Path Building
Manually concatenating backslashes is error-prone—if Fnumber or Fname ever ends with a backslash (unlikely here, but possible), you'll end up with double slashes that break the path. The BuildPath method handles this automatically, adding the correct separator only when needed:
Dim objFSO As Object Set objFSO = CreateObject("Scripting.FileSystemObject") ' Build the path step-by-step Dim Path As String Path = objFSO.BuildPath("Z:\Ebay\Suppliers Inventory", Fnumber) Path = objFSO.BuildPath(Path, Fname) ' If you specifically need a trailing backslash (most operations don't require it), add this: Path = objFSO.BuildPath(Path, "")
This method ensures your path is always formatted correctly, no matter what values are in Fnumber or Fname.
3. Debug the Generated Path
To confirm exactly what path your code is creating, add a debug statement right after concatenation. This will let you spot any unexpected characters or formatting issues:
' Add this after building your path Debug.Print "Generated Path: " & Path MsgBox "Generated Path: " & Path ' Optional, for visual confirmation
Check the Immediate Window (press Ctrl+G in the VBA editor) to see the exact string—this will quickly reveal if there's something off with the path.
4. Ensure the Folder Exists (If Needed)
If the path is "failing" because the folder doesn't exist, use FileSystemObject to create it recursively (it will make all parent folders if they're missing):
If Not objFSO.FolderExists(Path) Then objFSO.CreateFolder(Path) End If
Quick Recap
- Your SKU's hyphen isn't the problem—Windows allows hyphens in paths.
- Manual backslash concatenation is error-prone; use
BuildPathinstead for consistent results. - Clean up your variables to eliminate hidden whitespace or invalid characters.
- Debug the generated path to catch unexpected issues early.
内容的提问来源于stack exchange,提问作者EbayBill

