VBA范围1004错误

时间:2017-04-19 17:41:32

标签: excel vba excel-vba

我使用以下代码:

Sub CSVParser()

Dim i As Integer
Dim x As Integer
Dim values As Range

Sheets("CSV Paste").Select    
Range("A3").Select

For i = 1 To Range("A3", Range("A3").End(xlDown)).Rows.Count        
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Copy

    Sheets("Working Sheet 1").Select
    Range("A1").Select 'problem code

    Do Until ActiveCell.Value = ""
        If ActiveCell.Value = "" Then
            Exit Do
        Else
            ActiveCell.Offset(1, 0).Select
        End If
    Loop

    ActiveSheet.Paste
    Sheets("CSV Paste").Select                               
    ActiveCell.Offset(1, 0).Select                
Next

End Sub

然而,Range("A1").Select之后的行Sheets("Working Sheet 1").Select正在引发运行时错误' 1004'

有谁知道为什么?我已经用各种方式重新安排了这一点,我可以想到已经从头开始打字了。

3 个答案:

答案 0 :(得分:2)

尝试使用此版本的代码:

Sub CSVParser()

    Dim wb As Workbook
    Dim wsCSV As Worksheet
    Dim wsWork As Worksheet

    Set wb = ActiveWorkbook
    Set wsCSV = wb.Sheets("CSV Paste")
    Set wsWork = wb.Sheets("Working Sheet 1")

    wsCSV.Range("A3").CurrentRegion.Copy wsWork.Cells(wsWork.Cells.Count, "A").End(xlUp).Offset(1)

End Sub

答案 1 :(得分:2)

使用.Select和.Activate不被视为“最佳做法”。见How to avoid using Select in Excel VBA macros。是的,使用宏录制器中的代码是一个很好的起点,但你必须在某些时候远离练习。

执行批量操作比循环遍历不确定数量的行或列更好。

Option Explicit

Sub CSVParser()

    Dim lastCol As Long

    With Worksheets("CSV Paste")
        With .Range(.Cells(3, "A"), .Cells(.Rows.Count, "A").End(xlUp))
            lastCol = .CurrentRegion.Columns.Count
            With .Resize(.Rows.Count, lastCol)
                .Copy Destination:=Sheets("Working Sheet 1").Range("A1")
            End With
        End With
    End With

End Sub

答案 2 :(得分:1)

我认为这是你想要实现的目标(没有所有不必要的Select):

Option Explicit

Sub CSVParser()

Dim i As Long
Dim x As Long
Dim LastRow As Long
Dim PasteRow As Long

With Sheets("CSV Paste")
    LastRow = .Range("A3").End(xlDown).Row
    For i = 3 To LastRow
        PasteRow = Sheets("Working Sheet 1").Cells(Sheets("Working Sheet 1").Rows.Count, "A").End(xlUp).Row
        .Range(.Range("A" & i), .Range("A" & i).End(xlToRight)).Copy Destination:=Sheets("Working Sheet 1").Range("A" & PasteRow + 1)
    Next i
End With

End Sub