excel - 用for循环填充Excel文件
问题描述
我正在尝试使用 for 循环填充 Excel 文件,填充的逻辑是每 189 个结果执行一次,例如:
从 A1 填充到 A189 从 B1 填充到 B189
目前我有一个代码可以在第一行 A 上正常工作,但问题是当我尝试使用 B、C、D 等时。
这是我的代码:
'' I don't need first 4 results.
'' Total rows in this case is 569
For index as Integer = 5 To totalRows Step 1
Dim column as Integer = 2
'' var used to know if row is completed and change the ExcelProcess method
If rowsCompleted = 1 Then
'' realRows = 569 / 3 rounded down = 189
'' Flag initial value = 5 and is used as a internal index value instead of index var at for loop.
If flag <= realRows Then
'' copy
'' Excel Range = spreadsheet1.Cells(index, 7)
'' paste
'' Excel Range = spreadsheet2.Cells(8 * rowsCompleted - 6, index)
flag = flag + 1
Else
'' copy
'' Excel Range = spreadsheet1.Cells(index + 2, 7)
flag = flag + 1
'' paste
'' Excel Range = spreadshee2.Cells(8 * rowsCompleted - 6, flag)
End If
Else
rowsCompleted = rowsCompleted + 1
flag = 5
End If
Next
一步步调试我发现了一些重要的细节。
第一行包含 190 行,但不需要第一行,所以我只需要 189 行并从 5 开始。第二行和第三行包含 189 行,所以没有问题。我也需要从 5 行开始。
我还发现,我的代码第一行在 190 处结束。第二行必须在 379 处结束,但我发现它在 381 或 382 处结束。所以我认为问题可能出在我的 for 循环和索引或标志变量上。
另外我认为问题可能在于使用此代码复制值:
Excel Range = spreadsheet1.Cells(index + 2, 7)
因为我正在添加 + 2。
解决方案
为什么需要循环?
Range("A2:D189").Copy
spreadsheet2.range("A2").PasteSpecial xlpastevalues
一开始你说的不是很清楚你想要实现什么,Fill from A1 to A189 Fill from B1 to B189
但是你说 A 到 D 列这很好。
第二块文字说
First row contains 190 rows but the first one is not needed so I only need 189 rows and start on 5. second and third row contains 189 rows so there is no problem. Also I need to start on 5 row.
Also I found that with my code the first row ends fine on 190. second row must ends on 379 but I found that ends on 381 or 382. So I think that maybe the problem is with my for loop and index or flag vars.
当你说第一行包含 190 行但不需要第一行时,我很难理解你的意思(我假设你想要第 2 到 190 行?)但是你说你需要它从 5 行开始,所以我是不确定您是否希望它从第 5 行到第 5 行?
然后你说第二行必须在 379 结束,所以除了 190 加倍之外没有多大意义。
如果你想达到什么,你能给出一个更清晰的大纲吗?你想填充什么范围以及从哪里填充?
推荐阅读
- asp-classic - W3 Jmail 不工作(ActiveX 组件无法创建对象)
- sql - 从给定范围中选择最小值
- amazon-web-services - 到 API GW Authorizer 的 Cognito 回调令牌
- c# - 无法安装 .net 框架
- tensorflow - 获取 tfhub ALBERT 的词汇表
- nestjs - TypeORM 实体关系似乎不起作用
- python - 如何在python中制作动画堆积条形图
- reactjs - 使用 React Material 使表格适合页面
- java - 遍历 for 循环:为什么我的第一个 if 语句不运行?
- node.js - 将同一组件的功能分离到不同的文件中