我想打开一个文件(不是文件夹中的所有文件),添加一列,保存更改,然后关闭。我想遍历一些文件并执行相同的操作。
我用包含日期(yyyymmdd)的名称保存了文件,例如output_20181112_samples.csv
假设我要遍历两个文件output_20181113_samples.csv和output_20181114_samples.csv
我以为我可以使用I(迭代索引)并将其放在文件名的中间,但没有成功。我试图找到一种解决方案,但大多数答案都是遍历文件夹中的所有文件。
Sub open_add_col_save_close()
Dim i As Interger
For i = 1 To 10
Select Case i
Case 3, 4
Workbooks.Open Filename:="C:\Users\todd\Downloads\output_2018111" & i & "_samples.csv"
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
ActiveCell.FormulaR1C1 = "2018111" & i
ActiveCell.Offset(0, 0).Select
Selection.Copy
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.End(xlUp).Select
ActiveCell.FormulaR1C1 = "date"
Range("B2").Select
Workbooks("output_2018111" & i & "_samples.csv").Save
SendKeys "%s~"
Workbooks("output_2018111" & i & "_samples.csv").Close
End Select
Next i
End Sub
答案 0 :(得分:0)
尝试
Sub open_add_col_save_close()
Dim Fn As String
Dim Wb As Workbook
Dim Ws As Worksheet
Dim i As Integer
For i = 1 To 10
Fn = "C:\Users\todd\Downloads\output_2018111" & i & "_samples.csv"
Select Case i
Case 3, 4
Set Wb = Workbooks.Open(Filename:=Fn, Format:=2)
Set Ws = Wb.ActiveSheet
With Ws
.Columns("B:B").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
.Range("A1").End(xlDown).Offset(0, 1) = "2018111" & i
.Range("b1", .Range("b1").End(xlDown)) = "2018111" & i
.Range("b1") = "date"
End With
Wb.Save
Wb.Close (0)
End Select
Next i
End Sub