VBA - 复制值表1 - > sheet2,A505:A700> E2:E197但如果电池空白则停止

时间:2013-07-24 10:28:59

标签: vba copy

行动已经在标题中,我知道我已经关闭但被卡住了:

Dim wsS As Worksheet, wsU As Worksheet
Set wsS = Sheets("sheet1")
Set wsU = Sheets("non_confid")
Dim col1 As String, col2 As String, i As Long, j As Long
Set wsS = ActiveWindow.ActiveSheet
col1 = "A"
Set wsU = ActiveWindow.ActiveSheet
col2 = "E"
For i = 505 To 700
For j = 2 To 197
    If Not IsEmpty(ActiveCell.Value) Then
       wsS.Range(col1 & i).Copy
       wsU.Range(col2 & j).PasteSpecial xlPasteValues
    End If
Next i

*列表已经排序,因此它将以第一个空白单元格结束 提前谢谢!

2 个答案:

答案 0 :(得分:0)

为什么不简单地使用这样的东西:

    Sub kamal()

    Dim wsS As Worksheet, wsU As Worksheet
    Set wsS = Sheets("sheet1")
    Set wsU = Sheets("non_confid")

    For j = 2 To 197

    If Len(Trim(wsS.Range(A & j + 503).Value)) > 0 Then

     wsU.Range(col2 & j).Value = wsS.Range(col1 & j + 503).Value

    End If

    Next

    End Sub

或者一种简单的方法是使用公式。

答案 1 :(得分:0)

你的代码似乎有很多异常。我会在下面重构一下

Dim wsS As Worksheet
Dim wsU As Worksheet
Dim i As Integer

Set wsS = Sheets("sheet1") 'this has assigned the worksheet sheet1 to wsS
Set wsU = Sheets("non_confid") 'this has assigned the worksheet sheet1 to wsU

col1 = "A"
col2 = "E"

For i = 505 To 700
       If Not IsEmpty(wsS.Range(col1 & i).Value) Then
            wsU.Range(col2 & i - 503).Value = wsS.Range(col1 & i).Value
       End If

Next

其行为与您的代码类似,但应正确复制。我不确定你的问题是否只是想跳过空值或停止执行。要跳过范围中的空值,以下版本的代码将起作用。

Dim wsS As Worksheet
Dim wsU As Worksheet
Dim i As Integer
Dim j As Integer
Set wsS = Sheets("sheet1") 'this has assigned the worksheet sheet1 to wsS
Set wsU = Sheets("non_confid") 'this has assigned the worksheet sheet1 to wsU

col1 = "A"
col2 = "E"
j = 2

For i = 505 To 700
       If Not IsEmpty(wsS.Range(col1 & i).Value) Then
            wsU.Range(col2 & j).Value = wsS.Range(col1 & i).Value
            j = j + 1 'here is a new counter for the position on the second page.
       End If

Next

如果您希望循环在找到空单元格时停止,则以下代码应该有效。

Dim wsS As Worksheet
Dim wsU As Worksheet
Dim i As Integer
Dim j As Integer
Set wsS = Sheets("sheet1") 'this has assigned the worksheet sheet1 to wsS
Set wsU = Sheets("non_confid") 'this has assigned the worksheet sheet1 to wsU

col1 = "A"
col2 = "E"
j = 2

For i = 505 To 700
       If IsEmpty(wsS.Range(col1 & i).Value) Then
            Exit For 'this jumps out of the loop, so no more copying.
       Else
            wsU.Range(col2 & j).Value = wsS.Range(col1 & i).Value
            j = j + 1
       End If
Next