在一个程序中,此代码有效,在类似程序中,这表示复制单元格cell.value中的运行时错误1004

时间:2015-06-23 11:04:15

标签: excel excel-vba vba

在一个程序中,此代码有效,在类似的程序中,这显示了复制单元格cell.value中的运行时错误1004。

错误是列号未分配

Dim Next_6, PriceChange, Price_i, MyWorksheetLastRow As Long
MyWorksheetLastRow = Worksheets(1).Cells(Rows.Count, "A").End(xlUp).Row
Next_6 = ColInstance("Next_6_months", 1)
'Next_6 = 15
For Price_i = 2 To MyWorksheetLastRow
Cells(Price_i, Next_6).Value = Cells(Price_i, Next_6).Value & " " & Cells(Price_i, Next_6 + 1).Value
Next Price_i

Function ColInstance(HeadingString As String, InstanceNum As Long)
Dim ColNum As Long
On Error Resume Next
ColNum = 0
For X = 1 To InstanceNum
ColNum = (Range("A1").Offset(0, ColNum).Column) + Application.WorksheetFunction.Match(HeadingString, Range("A1").Offset(0, ColNum + 1).Resize(1, Columns.Count - (ColNum + 1)), 0)
Next
ColInstance = ColNum
End Function

在调试时,值15(与#34相匹配的列号; Next_6_months"未分配给Next_6)

为什么这样?

2 个答案:

答案 0 :(得分:1)

问题不是很明确,所以我猜。

您的代码有几点需要解决:

  1. 您必须完全符合Range 的资格。 此问题一次又一次出现(例如this)。

    这是什么意思?请勿使用CellsRangeRowsColumns而不指定Worksheet他们属于,除非你特别想要这样做(即使在这种情况下,明确使用ActiveSheet提高了可读性并减少了出错的可能性,类似于使用Option Explicit)。 例如,您使用

    MyWorksheetLastRow = Worksheets(1)...
    

    在某一时刻,在许多其他情况下,您不使用任何内容,默认为ActiveSheet。检查是否有意。

  2. 修复变量和函数的声明。 在模块的开头,使用

    Option Explicit
    

    然后解决此问题

    Dim Next_6 As Long, PriceChange As ..., Price_i As Long, MyWorksheetLastRow As Long
    

    Function ColInstance(HeadingString As String, InstanceNum As Long) As Long
    Dim ColNum As Long, X As Long
    

答案 1 :(得分:1)

如前所述,您的代码中有一些拼写错误声明变量,但您的ColInstance函数也可能无法始终返回您期望的内容

以下重写应该是有益的......

更新

稍微改变以允许行直接指向sheet1

Sub AssignValues()
    Dim Next_6 As Long, PriceChange As Long, Price_i As Long, MyWorksheetLastRow As Long
    With ThisWorkbook.Worksheets(1)
        MyWorksheetLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Next_6 = ColInstance("Next_6_months", 1)
        If Next_6 > 0 Then
            For Price_i = 2 To MyWorksheetLastRow
                .Cells(Price_i, Next_6).Value = .Cells(Price_i, Next_6).Value & " " & .Cells(Price_i, Next_6 + 1).Value
            Next Price_i
        End If
    End With
End Sub

Function ColInstance(Header As String, Optional Instance As Long = 1) As Long
    ' Function returns 0 if Header doesn't exist in specified row
    ' Function returns -1 if Header exists but number of instances < specified
    ColInstance = 0
    Dim i As Long: i = 1
    Dim c As Range

    With ThisWorkbook.Worksheets(1).Rows(1)
        Set c = .Find(Header, LookIn:=xlValues)
        If Not c Is Nothing Then
            FirstAdr = c.Address
            Do
                i = i + 1
                If i > Instance Then
                    ColInstance = c.Column
                    Exit Do
                End If
                Set c = .FindNext(c)
            Loop While c.Address <> FirstAdr
            If c.Address = FirstAdr And Instance > 1 Then ColInstance = -1
        End If
    End With
End Function