办公自动化:将包括软连字符的范围文本从 Word 复制到 Excel 或 Access,同时避免使用剪贴板

问题描述 投票:0回答:1

我正在拼命尝试将狭窄单词表的单元格内的文本(包括 MSWord 的自动连字符功能生成的软连字符)复制到 Excel 或 Access。 当表格单元格中已存在软连字符时,它就可以工作。 取消注释代码行后,第一次在 MSWord 中运行附加代码:

Option Explicit


Sub CopyWithHyphens()
  Dim oExc As Object, excWB As Object, excSheet As Object
  Dim myStart As Long, myEnd As Long, CopyRange As Range

  Const xlPasteValues = -4163
  
' when uncommenting the below lines, on my system, the softhyphens aren't available in the table cell until the Sub has finished,
' obviously auto-hyphenation cannot proceed during VBA processing?????
  
'    Dim TestTable As Table
'
''prepare table
'    With ActiveDocument
'      .AutoHyphenation = True
'      If .Tables.Count > 0 Then .Tables(.Tables.Count).Delete
'    End With
'    Set TestTable = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=1, NumColumns:= _
'                                                 1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
'                                                 wdAutoFitFixed)
'    With TestTable
'      .ApplyStyleHeadingRows = True
'      .ApplyStyleLastRow = False
'      .ApplyStyleFirstColumn = True
'      .ApplyStyleLastColumn = False
'      .ApplyStyleRowBands = True
'      .ApplyStyleColumnBands = False
'      .AllowAutoFit = False
'      With .Columns(1)
'        .SetWidth CentimetersToPoints(1.999), wdAdjustNone
'      End With
'      With .Cell(1, 1).Range
'        .Text = "This is a long text for demonstration of Autohypenation in a table cell"
'      End With
'    End With

  'select string to copy from the Table,
  'remove Cell-Text-End Marker (1 character)
  With ActiveDocument
'    .Paragraphs(1).Hyphenation = True
    myStart = .Tables(1).Cell(1, 1).Range.Start
    myEnd = .Tables(1).Cell(1, 1).Range.End - 1
    Set CopyRange = .Range(myStart, myEnd)
  End With

  CopyRange.Copy      'copy the selelcted range, now including also the soft hyphens within the text

  'open Excel
  Set oExc = CreateObject("Excel.Application")
  If Not oExc Is Nothing Then
    Set excWB = oExc.Workbooks.Add
    Set excSheet = excWB.worksheets(1)
    oExc.Visible = True

    excSheet.Range("A1").PasteSpecial xlPasteValues   'paste the text of the reduced CopyRange to Excel
  End If
  Set oExc = Nothing
  '..
End Sub

注释掉之前未注释的代码行后再次运行代码。 第一次运行未注释的代码会传输没有软连字符的字符串,第二次运行重新注释的代码也会传输软连字符,这是预期的行为。

使用剪贴板传输数据时多次运行程序非常不稳定,有人知道如何传输仍然包含软连字符的文本吗?

我尝试使用

range.xml
将数据存储在对象中,但不包括软连字符;使用
stringValue = range.text
的行为类似。

有人有想法吗?

excel automation ms-word vba7
1个回答
0
投票

使用 ConvertAutoHyphens 让我走上了正确的道路。至少在应用 ConvertAutoHyphens 后的中断模式下,变量 CopyRange 现在包括软连字符 (

Chr$(31)
),MSWord 用于条件连字符。 Copyrange 可以通过 Variant 传输到 Excel 或 Access

感谢您的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.