VBA 单元格选择 "application.union" with cells()

VBA cell selection "application.union" with cells()

我在选择子内容中两条不同行的部分时遇到问题。 我的 sub 必须用这些行创建一个图表 a DataSource,第二行的数字是该过程的一个参数。 CompteLigneDebutCompteColonnefin 是我之前定义的函数,它们 return 是一个整数。 这是导致问题的部分,导致错误的具体行是 set x... :

Sub test(ligne As Integer)
    Dim graphe As Chart
    Dim x As Range
    Set graphe = Charts.Add
    graphe.ChartType = xlColumnClustered
    Set x = Application.Union(Range(Cells(ligne, 2), Cells(ligne, CompteColonneFin)), Range(Cells(CompteLigneDebut, 2), Cells(CompteLigneDebut, CompteColonneFin - 1)))
    graphe.SetSourceData (x)

感谢您的help/advice

Union 看起来不错,下面的代码对我来说工作正常。我认为你的功能之一是问题所在。

Sub RunTheTest()

    test 3

End Sub
Sub test(ligne As Integer)
    Dim x As Range

    Set x = Application.Union(Range(Cells(ligne, 2), Cells(ligne, CompteColonneFin)), Range(Cells(CompteLigneDebut, 2), Cells(CompteLigneDebut, CompteColonneFin - 1)))

End Sub

Private Function CompteColonneFin() As Integer
    CompteColonneFin = 2
End Function

Private Function CompteLigneDebut() As Integer
    CompteLigneDebut = 2
End Function

尝试将 Application.Union 行分成更小的部分。然后检查函数 return.

的值
Sub test(ligne As Integer)
    Dim x As Range
    Dim colonneFin As Integer
    Dim ligneDebut As Integer

    colonneFin = CompteColonneFin()
    ligneDebut = CompteLigneDebut()

    Set x = Range(Cells(ligne, 2), Cells(ligne, colonneFin))
    Set x = Application.Union(x, Range(Cells(ligneDebut, 2), Cells(ligneDebut, colonneFin - 1)))

End Sub