You can't put an Asterix in a filename, you also forgot to include a blackslash in your copy command.
Sub MoveInvoices()
Dim ws As Worksheet
Dim folderPath, invoiceNumber, userNumber, invoiceFileName, userFolder As String
' Set worksheet
Set ws = ThisWorkbook.Sheets("serviceinvoice")
' Get folder path from cell D1
folderPath = ws.Range("D1").Value
' Loop through rows
For i = 3 To ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
invoiceNumber = Left(ws.Cells(i, 2).Value, 12) ' Use only the first 12 characters
userNumber = Left(ws.Cells(i, 1).Value, 4) ' Use only the first four characters
' Construct file paths
invoiceFileName = invoiceNumber & ".pdf" ' Assumes invoice files are PDFs
userFolder = userNumber ' The user folder starts with the user number
' Check if invoice file exists
If Dir(folderPath & "" & invoiceFileName) <> "" Then
' Check if user folder exists, if not, skip this invoice
If Dir(folderPath & "" & userFolder, vbDirectory) <> "" Then
' Move invoice to user subfolder
FileCopy folderPath & "" & invoiceFileName, folderPath & "" & userFolder & "\" & invoiceFileName
Kill folderPath & "" & invoiceFileName ' Remove original file
End If
End If
Next i
End Sub
Note: This assumes that the value in D1 ends with a backslash.
Bookmarks