1

我想检查我的选择是否包含 MergeCells,如果是,我不想在 excel 中处理该选择。但是每当我调用 selection.MergeCells 时,原始选择会发生变化,它会包裹我不想要的 MergeCells 所界定的区域。我已经检查了下面的 MSDN 链接,它表明这是一个限制/错误并且无法解决,所以任何人都可以帮助我吗?

http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/63920347-c731-4046-b96f-3f3e7eabddd8

4

2 回答 2

0

我跑过这篇文章,发现答案不起作用。

要了解原因,请尝试此代码

Cells.UnMerge
Cells.ClearFormats

[4:4,11:11,21:21].Select

Selection.Interior.Color = vbYellow

[a2:b5].Merge
[a19:b22].Merge

Debug.Print Selection.Address
Debug.Print [a1].MergeCells
Debug.Print Selection.Address
End Sub

唯一的solution is something like the following. Sorry I don't have time to flesh it out anymore.

dim mergedCells as collection, oldSelAddress as string, var as variant

oldSelAddress = selection.address
debug.print [a1].mergecells
if oldSeladdress <> selection.address then 
   set mergedCells = collectMergedCells(selection)
   selection.unmerge
   range(oldseladdress).select
   for each var in mergedCells
          var.merge
   next
end if 
于 2018-10-18T16:25:33.850 回答
-1

The problem in your case is slightly different from the link that you point to (because they are in the SelectionChanged event). In your case, the problem is that you are using Selection.MergeCells in you VBA code. Don't do that.

You should always avoid using Select-related actions in your own VBA code (because it is slow and worse, has tons of unintended side-effects, like this). Instead, use range objects. But because the Selection Range itself is so closely bound to the Selection object, you may need to disassociate it, like so:

Dim rng As Range, ws As Worksheet
'get the current worksheet
Set ws = ActiveSheet
'get the selection-range
Set rng = Selection
'get the same range, but disassociated from the selection
'(I think this works?)
Set rng = ws.Range(rng.AddressLocal)

If rng.MergeCells Then ...

Let me know if this does not work (I cannot test it right now), as there is a more complicated approach that can be used intead.

于 2013-05-08T14:48:28.810 回答