使用“select”和“范围”时未设置VBA对象variables

我试图在Excel VBA中拆分包含一些值的行。 问题是不分裂和复制行(我还没有!),但在方法'Application.Intersect'。 我想我通过2范围但程序崩溃与错误“对象variables或块variables未设置”。 当我打印他们时,我看到像“$ A $ 2 $ C $ D false”取决于我select了什么…我做错了什么?

我有这个代码,

Sub SplitRows() Dim LastRow As Long, _ WS1 As Worksheet, WS2 As Worksheet, _ i As Long, j As Integer, ii As Long, X, Y, _ MySelection As Range Set WS1 = Sheets("Foglio1") Set WS2 = Sheets("Foglio2") LastRow = Range("A" & Rows.Count).End(xlUp).Row With WS1 .Range(.Cells(1, 1), .Cells(1, Columns.Count)).Copy End With With WS2 .Cells(1, 1).PasteSpecial End With Application.CutCopyMode = False For i = 2 To LastRow Dim A As Range, SplitSize As Long For ii = 1 To Columns.Count Set A = WS1.Cells(i, ii) Set MySelection = Selection MsgBox A.Address & " " & MySelection.Address & " " & (Application Is Nothing) If Not (Application.Intersect(A, MySelection)) Is Nothing Then SplitSize = UBound(Split(WS1.Cells(i, ii).Value, ",")) Exit For End If Next ii MsgBox "SplitSize is" & SplitSize Next i End Sub 

解决scheme这里只需要replace这个

 If Not (Application.Intersect(A, MySelection)) Is Nothing Then 

接着就,随即

 If Not (Application.Intersect(A, MySelection) Is Nothing) Then 

你必须先分配一个对象到交叉点,然后检查它是否是空的:

  Set isect = Application.Intersect(A, MySelection) If Not isect Is Nothing Then