我有数千个带有特定文件名的.csv文件。 每个.csv文件都将第一行作为标题,将以下行(通常为20行)作为数据。 我需要帮助将每个.csv文件的文件名复制到最后一列20行,并且需要遍历文件夹中的所有.csv文件。
提前致谢!
答案 0 :(得分:1)
这应该这样做。根据您的操作,您可能需要更改它,以便它不会添加文件名字段(如果已存在)。等
Public Sub UpdateFiles()
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim xl As New Excel.Application
Dim wb As New Excel.Workbook
Dim lastRow
Dim lastColumn
Dim folder
'Change this folder to the one you want.
Set folder = fso.getFolder("c:\notbackedup\")
'Uncomment to watch/debug code
'xl.Visible = True
For Each f In folder.Files
Debug.Print f.Name
If (f.Name Like "*.csv") Then
Set wb = xl.Workbooks.Open(f.Path)
lastRow = wb.Sheets(1).UsedRange.Rows.Count
lastColumn = wb.Sheets(1).UsedRange.Columns.Count
wb.Sheets(1).Range(ColumnLetter(lastColumn + 1) & "1").Value = "FileName"
wb.Sheets(1).Range(ColumnLetter(lastColumn + 1) & "2:" & ColumnLetter(lastColumn+1) & lastRow).Value = f.Name
wb.Save
wb.Close True
End If
Next
xl.Quit
End Sub
Function ColumnLetter(ByVal ColumnNumber As Long) As String
Dim n As Long
Dim c As Byte
Dim s As String
n = ColumnNumber
Do
c = ((n - 1) Mod 26)
s = Chr(c + 65) & s
n = (n - c) \ 26
Loop While n > 0
ColumnLetter = s
End Function