我正在尝试整理支出,并且我的excel文档中的第一张纸包含了我的所有购买记录。我在A列中具有“日期”,在B列中具有“费用类别”,在C列中具有“详细信息”,在D列中具有“成本”。如果B列具有单词“ Gas”,我想将整行复制到工作表2中
我试图查找此问题,并从以下链接中找到了代码: https://www.extendoffice.com/documents/excel/3723-excel-move-row-to-another-sheet-based-on-cell-value.html#a1
我试图更新代码以反映我的数据,但是我刚刚开始学习VBA,并且收到“下标超出范围”错误和“ I = Worksheets(“ Sheet1”)。UsedRange.Rows.Count正在突出显示为黄色。
这是我当前的代码,基于将行复制到其他工作表的网站代码:
Sub MoveRowBasedOnCellValue()
Dim xRg As Range
Dim xCell As Range
Dim I As Long
Dim J As Long
Dim K As Long
I = Worksheets("Sheet1").UsedRange.Rows.Count
J = Worksheets("Sheet2").UsedRange.Rows.Count
If J = 1 Then
If Application.WorksheetFunction.CountA(Worksheets("Sheet2").UsedRange) =
0 Then J = 0
End If
Set xRg = Worksheets("Sheet1").Range("B1:B" & I)
On Error Resume Next
Application.ScreenUpdating = False
For K = 1 To xRg.Count
If CStr(xRg(K).Value) = "Gas" Then
xRg(K).EntireRow.Copy Desitination:=Worksheets("Sheet2").Range("A" & J + 1)
J = J + 1
End If
Next
Application.ScreenUpdating = True
End Sub
非常感谢您的帮助!
答案 0 :(得分:2)
我相信您需要更改
For K = 1 To xRg.Count
If CStr(xRg(K).Value) = "Gas" Then
xRg(K).EntireRow.Copy Destination:=Worksheets("Sheet2").Range("A" & J + 1)
J = J + 1
End If
针对:
For each KCell in xRg
If KCell.Value = "Gas" Then
KCell.EntireRow.Copy Destination:=Worksheets("Sheet2").Range("A" & J + 1)
J = J + 1
End If
Next KCell
(遍历xRg
中的每个单元格)