VBA - 运行此代码时出现运行时错误“1004”

时间:2017-08-08 12:27:17

标签: excel vba excel-vba

我是VBA的新手,我正在尝试将两个不同的列合并到另一个工作表的一列中。

我的问题是我收到“运行时错误'1004'应用程序或对象定义的错误”。

据我所知,错误最有可能与Sheets("Tabelle1")有关,但我不知道如何解决。

以下是代码:

Sub test2()
    Dim name1 As Range, size As Integer
    size = WorksheetFunction.CountA(Columns(3))

    With Sheets("Tabelle1")
        For Each name1 In Sheets("advprsrv").Range("D2:D" & size)
            If Not (Trim(name1.Value & vbNullString) = vbNullString) Then
                .Cells(name1.Row, 1).Value = LCase(name1.Value & " " & Range(Cells(name1.Row, name1.Column)))
            End If
        Next name1
    End With
End Sub

编辑:我使用F8查看了代码,似乎该行ws.Cells(name1.Row, 1).Value = LCase(name1.Value & " " & Range(Cells(name1.Row, name1.Column).Value))

出现错误

1 个答案:

答案 0 :(得分:1)

尝试下面的代码,代码注释中的解释:

Option Explicit

Sub test2()

    Dim name1 As Range, size As Long
    Dim TblSht As Worksheet
    Dim advpSht As Worksheet

    ' set the worksheet object and trap errors in case it doesn't exist
    On Error Resume Next
    Set TblSht = ThisWorkbook.Worksheets("Tabelle1")
    On Error GoTo 0
    If TblSht Is Nothing Then ' in case someone renamed the "Expense" Sheet
        MsgBox "Tabelle1 sheet has been renamed", vbCritical
        Exit Sub
    End If

    ' set the worksheet object and trap errors in case it doesn't exist
    On Error Resume Next
    Set advpSht = ThisWorkbook.Worksheets("advprsrv")
    On Error GoTo 0
    If advpSht Is Nothing Then ' in case someone renamed the "Expense" Sheet
        MsgBox "advprsrv sheet has been renamed", vbCritical
        Exit Sub
    End If

    With advpSht
        ' safer way to get the last row from column "D" (since later on you use it in a Range in Column "D")
        size = .Cells(.Rows.Count, "D").End(xlUp).Row

        For Each name1 In .Range("D2:D" & size)
            If Trim(name1.Value2) <> "" Then
                ' ***** Not sure about the connection between the 2 sheets *****
                TblSht.Cells(name1.Row, 1).Value = LCase(name1.Value2 & " " & TblSht.Cells(name1.Row, name1.Column))
            End If
        Next name1            
    End With

End Sub