首页 > 解决方案 > 保存输出文件从 Microsoft Word 中的表中创建了特定的行和单元格

问题描述

我需要从我的 word 文档中的表格中的特定行和单元格中获取一个字符串,并将其自动保存为我的输出文件名。例如,第 1 行单元格 1 的名称为“Samuel”。所以我想取那个名字,让它成为我创建的输出文件中的文件名。所以在我的代码中,我已经创建了一种基于之前的 if 条件创建输出 2 文件的方法。现在只需将文件自动保存为我为其指定的位置即可。这是我的代码:

Private Sub GenerateButton_Click()
Dim CellText As String
Dim i As Long

For i = 1 To 4

CellText = ActiveDocument.Tables(i).Rows(1).Cells(1).Range.Text
CellText = TrimCellText(CellText)

If CellText = "Module name" Then
            Dim fso As New FileSystemObject
            Dim ood As New FileSystemObject
            Dim filestream As TextStream
            Set filestream = fso.CreateTextFile("filepath", True)
            Set filestream = ood.CreateTextFile("filepath", True)
End If
Next
End Sub

Function TrimCellText(sCellText) As String
    Dim sLastChar As String

    sLastChar = Right(sCellText, 1)
    Do While sLastChar = Chr(7) Or sLastChar = Chr(13)
        sCellText = Left(sCellText, Len(sCellText) - 1)
        sLastChar = Right(sCellText, 1)
    Loop
    TrimCellText = sCellText
End Function

标签: vbams-word

解决方案


您只查看第一个单元格中的内容,但您要检索的数据位于它旁边的单元格中。尝试:

Private Sub GenerateButton_Click()
Dim fso As New FileSystemObject
Dim filestream As TextStream
Dim CellText As String
Dim i As Long

With ActiveDocument
  For i = 1 To 4
    If Split(.Tables(i).Cells(1, 1).Range.Text, vbCr)(0) = "Module name" Then
      CellText = Split(.Tables(i).Cells(1, 2).Range.Text, vbCr)(0)
      Set filestream = fso.CreateTextFile(CellText, True)
    End If
  Next
End With
End Sub

注意:我省略了 'Dim ood As New FileSystemObject' 和 'Set filestream = ood.CreateTextFile("filepath", True)' 因为它们看起来是多余的。我还重新定位了“Dim fso As New FileSystemObject”和“Dim filestream As TextStream”,因为我怀疑您是否需要在循环的每次迭代中重新创建它们。


推荐阅读