【发布时间】:2015-02-10 21:26:49
【问题描述】:
这是我第一次尝试 VBA,所以我为我的无知道歉。情况如下:我有一个由 4 列和 629 行组成的电子表格。当我试图做的是遍历每行中的 4 个单元格并检查一个空白单元格。如果有一行包含空白单元格,我想从 Sheet1 中剪切它并将其粘贴到 Sheet2 中的第一个可用行中。
(理想情况下,列数和行数是基于每个电子表格的动态的,但我不知道如何动态地遍历行和列)
Sub Macro1()
'
' Macro1 Macro
' Move lines containing empty cells to sheet 2
'
' Keyboard Shortcut: Ctrl+r
'
Dim Continue As Boolean
Dim FirstRow As Long
Dim CurrentRow As Long
Dim LastRow As Long
Dim EmptySheetCount As Long
Dim Counter As Integer
'Initialize Variables
LContinue = True
FirstRow = 2
CurrentRow = FirstRow
LastRow = 629
EmptySheetCount = 1
'Sheets(Sheet1).Select
'Iterate through cells in each row until an empty one is found
While (CurrentRow <= LastRow)
For Counter = 1 To 4
If Sheet1.Cells(CurrentRow, Counter).Value = "" Then
Sheet1.Cells(CurrentRow).EntireRow.Cut Sheet2.Cells(EmptySheetCount, "A")
EmptySheetCount = EmptySheetCount + 1
Counter = 1
CurrentRow = CurrentRow + 1
GoTo BREAK
Else
Counter = Counter + 1
End If
Counter = 1
BREAK:
Next
Wend
End Sub
当我运行它时,我通常会在 Sheet1.Cells(CurrentRow, Counter).Value = "" 区域出现错误,所以我知道我错误地引用了工作表。我已经尝试过 Sheets(Sheet1)、Worksheets("Sheet1"),但似乎没有任何效果。但是,当我更改为 Worksheets("Sheet1") 时,它会运行并冻结 Excel。
我知道我做错了很多事情,我只是知道得太少,不知道是什么。
提前非常感谢。并且对于垃圾格式感到抱歉。
【问题讨论】: