【发布时间】:2020-12-11 00:08:08
【问题描述】:
我想要做的很简单,我对 VBA 的经验几乎是 0。不过,我有使用其他语言(java、js、c 等)编码的经验。
我要做的是遍历excel表的行,查看每行第一个单元格中的整数值是否在一定范围内,如果是,则复制整行并粘贴到将保存为 CSV 的新工作表中。
我能够遍历该列并检查每一行中的第一个单元格值,我现在需要知道如何获取相应的行,将其复制并粘贴到 CSV 表中。
例如,假设这是我要解析的 excel 表:
假设用户指定他们想要抓取该行第一个单元格中的值介于 3 和 9 之间的所有行(第 6-8、11、13-15 行)。然后,我的 VBA 代码将遍历所有行并仅抓取符合上述条件的行,然后将这些行发送到一个看起来像这样的新工作表:
这就是我的代码现在的样子,它沿着 A 列向下,并检查每行第一个单元格中的值。我不确定如何抓取每一行,然后将其发送到新工作表
Sub exportDesiredRowsToCSVSheet()
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = "myCSV"
MsgBox "Sheet 'myCSV' was created" 'create new sheet that I will save as CSV at the end
firstL = Application.InputBox("first line item num", "please enter num", , , , , , 1) 'gets user to input lower bound
lastL = Application.InputBox("last line item num", "please enter num", , , , , , 1) 'gets user to input upper bound
For Each Row In Range("A:A") 'go through rows in column A
For Each Cell In Row 'go through first cell in each row of column A
If Cell.Value >= firstL And Cell.Value <= lastL Then 'if the value in the cell is in the range
'Here I want to take the desired rows and copy/paste them to a the newly created 'myCSV' sheet
End If
Next
Next
End Sub
感谢任何帮助!
【问题讨论】:
-
你只需要一个循环。你也应该find the last row....
For Each cell in Range("A1:A" & lastRow)。您可以在这里只使用Range.AutoFilter而不是循环。