selection.cells.count返回值不对?

lxz_lz 2006-02-24 03:12:48
我发现了。。。要是用户选择的单元格是整列,selection.cells.count 返回的值是正确的,


要是用户选择的单元格是随意不是连续的话,selection.cells.count 返回的值就是1

怎么这样呢?

还有,在Word里ALT+F11切换到VBA宏编辑环境下运行宏里的代码,和我在VB里运行相同的代码效果不一样,VB里直接报错,VBA里运行通过。

Dim oCell As Cell, ColArray() As Byte, RowArray() As Integer
Dim CellsCount As Integer, N As Integer, myTable As Table
Dim myCell As Cell, Sel As Selection
Dim Doc As Document
'Set Doc = Documents.Item(ActiveDocument.Name)
'Doc.Select
' ActiveDocument.Select

With Selection '//----这句VB报错selection为nothing
If .Information(wdWithInTable) Then
If .Type <> wdSelectionIP Then
CellsCount = .Cells.Count
ReDim ColArray(CellsCount - 1)
ReDim RowArray(CellsCount - 1)
For Each oCell In Selection.Cells
ColArray(N) = oCell.ColumnIndex
RowArray(N) = oCell.RowIndex
N = N + 1
Next
'此处可以添加遍历文档代码
With ActiveDocument
Set myTable = .Tables(2)
For N = 0 To CellsCount - 1
Set myCell = myTable.Cell(RowArray(N), ColArray(N))
Debug.Print .Range(myCell.Range.Start, myCell.Range.End - 1)
Next
End With
End If
End If
End With
...全文
241 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hero_8080 2006-03-04
  • 打赏
  • 举报
回复
高手~~
lxz_lz 2006-02-27
  • 打赏
  • 举报
回复
嗯,谢谢楼上朋友。
我又发现了。。。要是用户选择的单元格是整列,selection.cells.count 返回的值是正确的,要是用户选择的单元格是随意不是连续的话,selection.cells.count 返回的值就是1
faysky2 2006-02-27
  • 打赏
  • 举报
回复
With Selection '//----这句VB报错selection为nothing
--------------------------------------------------------------
Selection没有指定所属对象,而且,并不是直接把宏复制到vb里就能用,需要创建Word对象,请参考:

Private Sub Command1_Click()
......
Dim wordApp As Object
Set wordApp = CreateObject("word.application") '创建Word对象

wordApp.Visible = True
Dim myDoc As Object
Set myDoc = wordApp.Documents.Open("c:\Test.dot") '打开Word文件

With wordApp.Selection '//----这句VB报错selection为nothing
If .Information(wdWithInTable) Then
......

'此处可以添加遍历文档代码
With wordApp.ActiveDocument '这里也要指定所属对象
......

'myDoc.Close
'wordApp.Quit
Set myDoc = Nothing
Set wordApp = Nothing
End Sub
lxz_lz 2006-02-27
  • 打赏
  • 举报
回复
帮看看...

2,462

社区成员

发帖
与我相关
我的任务
社区描述
VBA(Visual Basic for Applications)是Visual Basic的一种宏语言,是在其桌面应用程序中执行通用的自动化(OLE)任务的编程语言。
社区管理员
  • VBA
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧