excel - Excel VBA:循环遍历行,同时按顺序分隔日期跨度
问题描述
我正在尝试找到一种方法来遍历命名表中的行,将每一行复制到另一个表中,并在每一行末尾的空白字段中添加一个值,该字段对日期跨度之间的日期进行排序。
我遇到了可以成功地将日期跨度分成行的代码,但是在创建循环以遍历每一行数据并复制其余数据时遇到了麻烦。
表格中的数据示例(带标题):
表名:TblOGCalendar 表名:OGCalendarData
应该复制过来如下所示:
表名称:TblR2Calendar 表名称:R2CalendarData
这也对我正在从事的另一个项目产生影响,在该项目中,他们希望跟踪和预测项目工作的员工时间。
解决方案
is 绝不是一个答案,但更适合帮助你学习东西
可以通过各种方式循环遍历 excel 文件 - 有些好,有些坏。仅取决于您使用代码的技能水平和舒适度。
我只会概述 2 种方法
方法 #1 - 循环遍历行/列本身。我不喜欢这种方法,因为它是一种不好的做法——与应用程序对象交互是性能杀手。
dim rng as range, rcell as range
' you have to tell the compiler where stuff is at
' this is important and a commmon mistake that causes quesitons her eon SO
set rng = Thisworkbook.worksheets("Yoursheetname").Range("yourrange")
for each rcell in rng.Cells
'rcell is the current cell in the range you're looping through.
'Will physically loop through cells top to bottom, left to right
' do some processing.
next rcell
方法 #2 - 使用数组在内存中工作。这是首选方法,如果您计划在未来更频繁地使用 excel-vba,您应该擅长的方法。
dim arr as variant ' you need this for dumping sheet to arrays
dim i as long, j as long
arr = THisworkbook.Worksheets("yoursheet").UsedRange
' there are many ways to get the desired range of a sheet - pick your favorite (after researching), and use that.
' the ubound and lbound functions literally mean upper and lower. It basically says for i equal beginning of array dimension to last.
' the number dictates what dimension of the array you want to loop through. Excel ranges are mutlidimensional by default. 1 = rows, 2 = columns
for i = LBound(arr,1) to UBound(arr,1)
for j = LBound(arr,2) to UBound(arr,2)
' do some processing
' array values can be accessed through this methods
' arr(i,j)
' arr(i, x) x being a number, like if you know i want column 7 of current iteration/row
' arr(i+1, j-1) plus values move down, or to the right (depending on dimension) while negative value go up or left (depending on dimension)
next j
next i
'to put stuff back on your sheet after processing
thisworkbook.worksheets("yoursheet").range("yoursheet").value = arr
这应该让你继续自己解决问题
推荐阅读
- php - 是否有可能获得函数的静态值?
- javascript - firebase.database() 不是函数
- omnet++ - 在 Omnet++/Veins、SUMO 中更改交通灯颜色错误
- java - JComboBox 擦除它弹出的 JComponent
- javascript - 在猫鼬中更新许多
- android - 地图片段(Kotlin)onMapReady 不工作
- c++ - 如何制作一个接受 2 个参数而不是 1 的递归 lambda 函数?
- oracle - 如何从 SSIS/Visual Studio 建立到 ORACLE 的 ODBC 连接?
- javascript - 您如何判断 HTML5 视频是实时流还是仅来自 Javascript 的视频?
- mongodb - 在保留根字段的同时对子文档进行分组/计数