为 vba 使用 for 循环
Posted
技术标签:
【中文标题】为 vba 使用 for 循环【英文标题】:using for loop for vba 【发布时间】:2015-03-17 04:27:39 【问题描述】:在循环中运行下面的代码 35 次,然后...还将 file1 替换为增量值,并将 Rannge("D6") 增量为 range("D7") 等等。
使用 for 循环并迭代 35 次递增 file1 和 d6 单元格
Windows(File1).Activate
Range("A1").Select
Selection.End(xlToRight).Select
ActiveCell.Offset(0, -2).Range("A1:B1").Select
ActiveCell.Columns("A:B").EntireColumn.Select
ActiveCell.Offset(27961, 0).Range("A1").Activate
Application.CutCopyMode = False
Selection.Copy
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Result"
ActiveSheet.Paste
Range("C1").Value = "Year"
Range("C2").Select
ActiveCell.FormulaR1C1 = "=LEFT(RC[-2],4)"
Selection.AutoFill Destination:=Range("C2:C" & Range("B1048576").End(xlUp).Row)
Dim year As Integer
year = InputBox("Fill in year")
Dim week As Integer
week = InputBox("Fill in week")
Cells(1, 4) = "YEAR"
Range("C2:C" & Range("C1048576").End(xlUp).Row).Select
Selection.Copy
Range("D2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Cells(1, 5) = "Values"
Cells(2, 5).Select
ActiveCell.FormulaR1C1 = "=IF(AND(RC[-1]=" & year & ",RC[-3]=" & week & "),1,0)"
Selection.AutoFill Destination:=Range("E2:E" & Range("D1048576").End(xlUp).Row)
Range("D:D").Select
With Selection
Selection.NumberFormat = "0"
.Value = .Value
End With
Range("F2").Select
ActiveCell.FormulaR1C1 = "=SUM(RC[-1]:R[98576]C[-1])"
ActiveCell.Select
Cells(2, 6).Select
Selection.Copy
Windows("Penetrace Macros.xlsm").Activate
Sheets("Book1withCount").Activate
Range("D6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveCell.Offset(1, 0).Select
Windows("Penetrace Macros.xlsm").Activate
Application.DisplayAlerts = False
Windows(File1).Activate
Sheets("Result").Select
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
Workbooks(File1).Close SaveChanges:=False
Windows("Penetrace Macros.xlsm").Activate
Range("A1").Select
【问题讨论】:
你的问题有问题吗? 我想在循环中运行上面的代码,这是我的问题,并将提到的 file1 增加为 file1、file2 等 您是否尝试过将您的代码放入For j = 1 To 35
Next j
块中?请先自己尝试一下,如果遇到任何问题,请随时回来。
Dim loop_ctr As Integer Dim cell_ctr As Integer For loop_ctr = 1 To 3 For cell_ctr = 6 To 8 Dim filename As String filename = 'File' & loop_ctr Windows(filename).Activate 但在这里我该怎么做提到像 Windows 中的 file1 激活。因为我正在连接文件和变量值,但它不读取为 file1
【参考方案1】:
你能试试这个吗?想法应该是这样的。
Dim FileNo As String
For i = 1 To 35
FileNo = "File" & i
Windows(FileNo).Activate
'Rest of the code
Next
【讨论】:
我尝试了同样的事情 Dim loop_ctr As Integer Dim cell_ctr As Integer For loop_ctr = 1 To 3 For cell_ctr = 6 To 8 Dim filename As String filename = "File" & loop_ctr Windows(filename).Activate这给了我一个错误 windows(filename).Activate 嗨,我想你也需要使用扩展。比如:Windows(文件名和“.txt”)。激活。除此之外,您需要在运行代码时打开相关文件,如果它未打开,它将无法正常工作。以上是关于为 vba 使用 for 循环的主要内容,如果未能解决你的问题,请参考以下文章