在一个程序中这个代码工作,并在类似的程序中显示运行时错误1004在复制cell.value

在一个程序中这个代码工作,并在类似的程序中显示运行时错误1004在复制cell.value。

错误是列号不分配

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 

在debugging时,值15(匹配“Next_6_months”的列号不分配给Next_6)

为什么这样?

问题不是很清楚,所以我会猜测。

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

  1. 你必须完全符合你的Range 。 这个问题一再出现(例如, 这个 )。

    这是什么意思? 不要使用CellsRangeRowsColumns而不指定它们属于哪个Worksheet ,除非你特别想这样做(甚至在这种情况下,显式地使用ActiveSheet可以提高可读性并减less错误发生的机会,类似于使用Option Explicit ) 。 比如你用

     MyWorksheetLastRow = Worksheets(1)... 

    在许多情况下,你什么也不用,默认是ActiveSheet 。 检查这是否是有意的。

  2. 修正variables和函数的声明。 在模块的开始处,使用

     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 

正如前面提到的那样,在你的代码中有一些错误的声明variables,但它也可能是你的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