【发布时间】:2015-01-01 20:49:51
【问题描述】:
我正在尝试拆分 Excel VBA 中包含某些值的行。问题不在于拆分和复制行(我还没有!),而在于方法“Application.Intersect”。我想我正在传递 2 个范围,但程序崩溃并出现错误“对象变量或未设置块变量”。 当我打印它们时,我会看到类似“$A$2 $C$D false”的内容,具体取决于我选择的 wath... 我做错了什么?
我有这个代码,
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
解决方案在这里 替换这个
If Not (Application.Intersect(A, MySelection)) Is Nothing Then
这样
If Not (Application.Intersect(A, MySelection) Is Nothing) Then
【问题讨论】:
-
你能检查一下这一行吗,Set MySelection = Selection。正如您之前在代码中使用的那样,Application.CutCopyMode = False,没有可用于将其分配给 MySelection 的活动选择。你能检查一下吗?
-
刚刚在您发表评论后检查过......不幸的是,即使没有“Application.CutCopyMode = False”,结果也是一样的......
-
选择是从哪个工作表中选择范围?如果是 sheet1,那么在 MySelection = Selection 之前尝试 WS1.Activate
-
您是否尝试过单步执行您的代码以查看究竟是哪一行引发了错误?
-
行是 If Not (Application.Intersect(A, MySelection)) Is Nothing Then