0

我正在使用电子表格,本质上我想在之前保存的给定范围的末尾添加一些文本。我搜索了论坛并遇到了各种似乎给出各种结果的技术。

我使用了以下代码:

foreach (Excel.Range row in MyGivenRange.Rows)
{
    Excel.Range cell = (Excel.Range)row.Cells[1, 1];
    cell.Value += "Add this text";
}         

这会将文本一个接一个地添加到范围内每个单元格的末尾,但是因为我的电子表格中有 11k 条记录,这需要一段时间。有什么捷径可以走吗?我已经尝试过各种作为复制和粘贴值。我可以在旁边的列中快速粘贴一些文本然后合并以节省时间吗?

只是想知道你们是否有任何想法我能做什么。对我来说,搜索每一行可能效率很低。和以前一样,我发现使用范围直接复制粘贴之前节省了我的时间。也许有一种特殊的方法可以在给定的列或范围上使用插入来立即调整每个实例?

4

1 回答 1

0

This is vba, but it should be fairly easy to convert to C#.

I wrote this in response to your question. Using testit updates approximately 16000 cells, and took about 6 seconds. The basic idea is to copy the Excel formulas into an array, update the array, and then paste the array back into Excel as the formulas.

Sub testit()
appendTextToRange "A1:D4000", "hey there"
End Sub

Sub appendTextToRange(rngAddress As String, append As String)
Dim arr() As Variant, c As Variant
arr = Range(rngAddress).Formula
For x = LBound(arr, 1) To UBound(arr, 1)
    For y = LBound(arr, 2) To UBound(arr, 2)
        Debug.Print arr(x, y)
        If arr(x, y) = "" Then
            arr(x, y) = append
        ElseIf Left(arr(x, y), 1) = "=" Then
            arr(x, y) = arr(x, y) & " & "" " & append & """"
        Else
            arr(x, y) = arr(x, y) & " " & append
        End If
    Next
Next
Range(rngAddress).Formula = arr
End Sub

Warning: If you update any fields that are used for calculation with this, you will break your calculations.

于 2012-07-23T18:24:18.553 回答