更改从Excel导入的数据在Word中的数字格式

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

我正在尝试更改从 Excel 工作表导入的数字格式,并以“0.00%”格式在 Word 文档表格中打印它们。

在 Excel 中预先更改格式是没有用的,因为转录数据时会粘贴原始数字。

Const stWordDocument As String = "Doc.docm"

Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdCell As Word.Cell
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim lnCountItems As Long
Dim vaData As Variant

Set wbBook = ThisWorkbook
Set wsSheet = wbBook.ActiveSheet
vaData = ActiveSheet.Range(Cells(1, "F"), Cells(rcount, lastcol0)).Value

Set wdApp = CreateObject("word.Application")
Set wdDoc = wdApp.Documents.Open("https://orgindustrie-my.sharepoint.com/personal/Different_person_org_com/Documents/folder/subfolder/subsubfolder/Doc.docm")
wdApp.Visible = True

For i = 1 To lastcol0 - 5 Step 1
    lnCountItems = 1
    For Each wdCell In wdDoc.Tables(1).Columns(i).Cells
        If lnCountItems = rcount + 1 Then
            Exit For
        Else
            Cell_Text = wdCell.Range.Text
            whte = IsNumeric(vaData(lnCountItems, i))
            If whte = True Then
                wdCell.Range.Text = Format(Cell_Text, "0.00%")
            End If
            wdCell.Range.Text = vaData(lnCountItems, i)
            lnCountItems = lnCountItems + 1
        End If
    Next wdCell
Next i

这会将所有 Excel 数据标识为数字,将所有 Word 数据标识为非数字,因此始终如此。

whte = IsNumeric(vaData(lnCountItems, i))

这也不会改变该行输出的格式

wdCell.Range.Text = Format(Cell_Text, "0.00%")

如果我将其更改为Word数据,它总是错误的。

whte = IsNumeric(Cell_Text)

它总是以这种形式出现

Word示例输出

Excel 示例源

我试过了

wdCell.Range.Text = FormatPercent(Cell_Text, 2)

但是出现错误“类型不匹配”。

我也尝试过

wdCell.Range.Text.NumberFormat = "0.00%"

此处,当我删除

.Text
时,出现错误“无效限定符”或“未找到方法或数据成员”。

这些数字来自

.Sumifs
线。

.Cells(i, lastcol).Value = Application.WorksheetFunction.SumIfs(Range(Cells(rcount, "E"), Cells(2, "E")), Range(Cells(rcount, "B"), Cells(2, "B")), Cells(i, "B"))
rcount= last row with information
lastcol0= last column with information 
lastcol= last column without information ( basically lastcol0 + 1 )
excel vba ms-word
1个回答
2
投票

也许更像这样?

For Each wdCell In wdDoc.Tables(1).Columns(i).Cells
    If lnCountItems = rcount + 1 Then
        Exit For
    Else
        v = vaData(lnCountItems, i)                   'get value from array
        If IsNumeric(v) Then v = Format(v, "0.00%")   'format if numeric
        wdCell.Range.Text = v                         'put in cell
        lnCountItems = lnCountItems + 1
    End If
Next wdCell
© www.soinside.com 2019 - 2024. All rights reserved.