excel

时间:2018-05-21 08:21:44

标签: excel vba excel-vba

当我处理大型csv文件时,我决定将它们加载到VBA内存中,而不是加载到我的电子表格中,以使其更快更轻。

所以我有一个函数CSVtoArray,它读取我的CSV并给我一个数组。

然后,如果我仍想在excel中查看我的数据,我只需在我的s / s中写{=(CSVtoArray(my_csv_path)}。

但是由于我的csv的大小随着时间的推移而变化,我想编写一个名为AutoRange的函数,它会根据我的范围大小自动调整电子表格中的显示区域。

所以这就是我写的,但是它不起作用,它什么都不做,只有我正在编写公式的单元格被填充。

    Function AutoRange(my_array As Variant)

        Dim nb_rows, nb_cols As Integer
        Dim current_cell, target_range As Range

        nb_rows = UBound(my_array, 1)
        nb_cols = UBound(my_array, 2)

        Set current_cell = Selection

        current_cell.Resize(nb_rows, nb_cols).FormulaArray = current_cell.Formula

        AutoRange = Selection

    End Function

先谢谢你们。

2 个答案:

答案 0 :(得分:0)

函数用于返回事物。如果在单元格中使用,则用于将事物返回到该单元格,而不是操纵其他单元格。你想要真正想要一个像?

<强>代码:

Option Explicit
Public Sub TEST()

    Dim my_Array()
    my_Array = [A1].CurrentRegion.Value
    Dim target_Range As Range
    Set target_Range = AutoRange(my_Array)

End Sub

Public Function AutoRange(ByVal my_Array As Variant) As Range

    Dim nb_rows, nb_cols As Long
    Dim current_cell, target_Range As Range

    nb_rows = UBound(my_Array, 1)
    nb_cols = UBound(my_Array, 2)

    Set current_cell = Selection
    Set target_Range = current_cell.Resize(nb_rows, nb_cols)
    Set AutoRange = target_Range

    target_Range.FormulaArray = current_cell.Formula

End Function

<强>结果:

Result

从你的评论:如果你想用作一个函数(不是UDF,它不能改变其他单元格),那么你可以使用以下方式,虽然我建议反对它,因为它是不好的做法:

sudo apt remove python pip

答案 1 :(得分:0)

好的,我这样做了,

我有我的AutoRange子:

    Sub AutoRange(my_Array As Variant, top_left_corner As Range)
        ' Here we take an array in input, the one we want to display, and the top left corner of the range where we want to put it

    Dim nb_rows, nb_cols As Integer

    nb_rows = UBound(my_Array, 1)
    nb_cols = UBound(my_Array, 2)

    Set current_cell = top_left_corner

    top_left_corner.Resize(nb_rows, nb_cols).FormulaArray = top_left_corner.Formula

    End Sub

然后我在我的s / s中添加了一个Worksheet_change子:

    Private Sub Worksheet_Change(ByVal Target As Range)
        If Target.Address = "$A$1" Then
            if Target.value="load data" then
                Call Autorange(my_array, my_range)
            else
                Range(my_range, my_range.End(xlDown).End(xlToRight)).clearcontents
        End If
    End Sub

所以我只想说是否要加载我的数据,它会调整。

我认为在我以前的公司,他们使用的是addin而不是VBA本身。

无论如何,谢谢你们。 欢呼声