-2
    Private Sub CommandButton1_Click()
Dim nbp As Long
Dim i As Long
Dim p As Long
  Dim FV As Variant
  Dim CS As Variant
  Dim K As Variant
  Dim iFV As Integer
  Dim iCS As Double

If Range("B9") = "Semi-Annual" Then
  
  p = DateDiff("yyyy", Cells(4, 3), Cells(5, 3))
  
nbp = p * 2
   
 For i = 5 To nbp + 4
        Cells(5, 10).Value = Cells(4, 3).Value
        Cells(i + 1, 10).Value = DateAdd("m", 6, Cells(i, 10).Value)
        
         Next i
  
For i = 6 To nbp + 5

    Cells(i, 14).Value = Cells(7, 2).Value * (Cells(8, 2).Value / 2)
    
Next i

 FV = Sheet2.Range("J5:J10").Value
  CS = Sheet3.Range("F1:G8000").Value

  For iFV = 1 To UBound(FV)

    For iCS = 1 To UBound(CS, 2)
  

      If FV(iFV, 1) = CS(iCS, 1) Then
      
        K(iFV, 1) = CS(iCS, 2)
      
      End If

    Next

  Next

   Sheet2.Range("K5:K10").Value = K

End If
 
 End If
 
If Range("B9") = "Annual" Then
 
    nbp = DateDiff("yyyy", Cells(4, 3), Cells(5, 3))
 
        For i = 5 To nbp + 4
        
            Cells(5, 10).Value = Cells(4, 3).Value
            Cells(i + 1, 10).Value = DateAdd("m", 12, Cells(i, 10).Value)

        Next i
    End if 
If Range("B9") = "Quarterly" Then
 
    p = DateDiff("yyyy", Cells(4, 3), Cells(5, 3))
    nbp = p * 4
    
        For i = 5 To nbp + 4
        
            Cells(5, 10).Value = Cells(4, 3).Value
            Cells(i + 1, 10).Value = DateAdd("m", 3, Cells(i, 10).Value)

         Next i
 
End If

 
If Range("B9") = "Monthly" Then ' to choose from a list . 
 
    p = DateDiff("yyyy", Cells(4, 3), Cells(5, 3))
    nbp = p * 12
    
        For i = 5 To nbp + 4
        
            Cells(5, 10).Value = Cells(4, 3).Value
            Cells(i + 1, 10).Value = DateAdd("m", 3, Cells(i, 10).Value)

        Next i
 
End If
 
End Sub

我已在按钮中添加了所有代码以提供帮助。我不确定这是否会有所帮助,反正就是这样。如果用户选择半年度,那么会发生几件事。其余的“ifs”也是如此,但我需要先解决这个问题,然后再处理其余的问题。代码太长,简单不复杂。

4

1 回答 1

0

现在发布了更多代码,我想我明白问题所在了。

无论您在何处引用Cells()VBA,都假定它适用于ActiveSheet. 而且我认为您应该完全限定呼叫是Sheet2.Cells()例如或任何您需要的。

当您调用按钮后面的代码时,该按钮位于工作表上,并且它引用该工作表上的单元格。但是,当您将代码移动到模块时,它不再引用带有按钮的工作表,而是当时处于活动状态的任何其他工作表。

因此,每当您在其前面看到Cells()Range()没有工作表规范时,请对其进行更改,以使其针对特定的工作表。

PS。避免使用,而是Integer更喜欢。Long此外,更喜欢相对引用,例如Sheet2.Range("G2").Cells(i,j)而不是绝对引用Sheet2.Cells(1+i, 6+j)或字符串数​​学,例如Sheet2.Range("G" & 1+i & ":G" & 5+i).

于 2020-12-27T19:32:20.730 回答