简体   繁体   English

如何建立 VBA 宏以将范围而不是单个单元格复制并粘贴到 MS Word 文档?

[英]How to establish VBA macro to copy and paste a range instead of singular cells to a MS Word doc?

I have a macro below that essentially takes an excel cell and pastes into a MS word table.我在下面有一个宏,它基本上采用 excel 单元格并粘贴到 MS 字表中。 Right now, I have 4 excel cells per "observation" that have to be copied and pasted into an MS word table that has 5 columns and two rows.现在,每个“观察”有 4 个 excel 单元格,必须将其复制并粘贴到具有 5 列和 2 行的 MS 字表中。 When pasting the cells (A, E, F, I), they need to go into column 1, 2, 3, and 5 respectively for the table.粘贴单元格(A、E、F、I)时,需要将 go 分别粘贴到表格的第 1、2、3 和 5 列中。

Does anyone know if there is a way to condense the below code to a simple range?有谁知道是否有办法将下面的代码压缩到一个简单的范围内? Instead of telling the macro to copy this, paste that, copy this, paste that.. etc., I would like to tell it to copy this range, paste it, then move to the next entire observation table.我不想告诉宏复制这个、粘贴那个、复制这个、粘贴那个..等等,我想告诉它复制这个范围、粘贴它,然后移动到下一个整个观察表。


    Dim tb13 As Excel.Range
    Set tb13 = ThisWorkbook.Worksheets("Observation Listing").Range("A10")
    tb13.Copy

    myDoc.Tables(4).Cell(Row:=2, Column:=1).Range.PasteExcelTable _
    LinkedToExcel:=True, _
    WordFormatting:=False, _
    RTF:=True
    
'Obs Summary
    Dim tb14 As Excel.Range
    Set tb14 = ThisWorkbook.Worksheets("Observation Listing").Range("E11")
    tb14.Copy

    myDoc.Tables(4).Cell(Row:=2, Column:=2).Range.PasteExcelTable _
    LinkedToExcel:=True, _
    WordFormatting:=False, _
    RTF:=True
    
'Pot. Bus. Impact
    Dim tb15 As Excel.Range
    Set tb15 = ThisWorkbook.Worksheets("Observation Listing").Range("F11")
    tb15.Copy

    myDoc.Tables(4).Cell(Row:=2, Column:=3).Range.PasteExcelTable _
    LinkedToExcel:=True, _
    WordFormatting:=False, _
    RTF:=True
    
'Action Plan
    Dim tb16 As Excel.Range
    Set tb16 = ThisWorkbook.Worksheets("Observation Listing").Range("I11")
    tb16.Copy

    myDoc.Tables(4).Cell(Row:=2, Column:=5).Range.PasteExcelTable _
    LinkedToExcel:=True, _
    WordFormatting:=False, _
    RTF:=True

You can use this: for expample by 'Obs Summary你可以使用这个:例如'Obs Summary

myDoc.Tables(4).Cell(2, 2).Range.text = _ 
        ThisWorkbook.Worksheets("Observation Listing").Range("E11").value

You can use this cycle to loop through the range and write all cell values into the table:您可以使用此循环遍历范围并将所有单元格值写入表中:

Dim rng As Range
Dim v As Variant
Dim col As Long, r As Long
Set rng = ThisWorkbook.Worksheets("ObservationListing").Range("A11:C11")
col = 1 'start with this column
r = 2 ' row
For Each v In rng.Cells
    myDoc.Tables(4).Cell(r, col).Range.Text = v.Value
    col = col + 1
Next v

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM