gpt4 book ai didi

excel - 函数更改工作表中的值

转载 作者:行者123 更新时间:2023-12-04 21:29:36 24 4
gpt4 key购买 nike

我正在创建一个原型(prototype)是:

Function TableToText(ByVal Table As Range) As String

这个函数应该给我一个字符串,根本不修改工作表。但是我在 Table 上执行的操作(这是一个 Range )函数内部也修改了我的工作表。

我以为 ByVal哪个是默认值应该防止这种情况?

我尝试在我的函数中创建另一个范围,但要创建另一个您使用的范围 Set所以无论如何它都不会解决问题......

有人可以指出我在这里缺少什么吗?先感谢您! :)

整个功能是
Function TableToText(Table As Range) As String
Dim nbColumns As Integer, nbRows As Integer
Dim i As Integer, j As Integer, s As Integer
Dim max As Integer, difference As Integer

nbColumns = Table.Columns.Count
nbRows = Table.Rows.Count
With Table
'' adding the spaces
For j = 1 To nbColumns
max = 0
' Find the longest string in the column
For i = 1 To nbRows
If Len(.Cells(i, j).Value) > max Then
max = Len(.Cells(i, j).Value)
End If
Next i

' Adding the spaces and the |
For i = 1 To nbRows
If Len(.Cells(i, j).Value) < max Then
difference = max - Len(.Cells(i, j).Value)
For s = 1 To difference
.Cells(i, j) = CStr(.Cells(i, j).Value) + " "
Next s
End If
.Cells(i, j) = CStr(.Cells(i, j).Value) + "|"
Next i
Next j

'' Creating the plain text table string
For i = 1 To nbRows
For j = 1 To nbColumns
TableToText = TableToText + .Cells(i, j).Value
Next j
TableToText = TableToText & vbCrLf
Next i
End With
End Function

最佳答案

此页面上有很多误导性信息和困惑。

I thought ByVal which is the default was supposed to prevent that?



默认为 ByRef在 VBA 中。这是不幸的,因为绝大多数时候,你的意思是传递东西 ByVal .

Objects are always passed by reference [...] ByVal is ignored.



不,对象永远不会“通过”,句号。 byref/byval 传递的是对对象的引用,即指针。 这并不意味着总是传递对象参数ByRef完全 .

让我们一劳永逸地揭穿这种说法。
Public Sub DebunkObjectsAreAlwaysPassedByRefClaim()
Dim thing As Collection 'any object type will do
Set thing = New Collection
DoSomethingByVal thing 'we pass a COPY of the pointer
Debug.Print thing.Count 'no problems here
DoSomethingByRef thing 'we pass a reference to our local pointer; what could possibly go wrong?
Debug.Print thing.Count 'error 91! the object reference is gone!
End Sub

Private Sub DoSomethingByVal(ByVal o As Object)
Set o = Nothing 'affects the local copy only
End Sub

Private Sub DoSomethingByRef(ByRef o As Object)
Set o = Nothing 'affects the same object pointer the caller gave us. this is bad.
End Sub
ByRef对比 ByVal有很大的不同:给一个过程你的对象指针( ByRef ),他们可以用它做任何他们喜欢的事情 - 包括 Set -将其分配给完全不同的对象引用,或将其设为 Nothing .给一个过程一个对象指针的副本( ByVal ),无论他们用它做什么(包括 Set -将它分配给一个完全不同的对象引用或使其成为 Nothing )只会影响该副本。

在这两种情况下,无论您是传递了指针本身还是它的副本,无论哪种方式,您都在为过程提供对同一对象的访问权限,因此 as GSerg explained , 任何影响 Range 的指令(您无法创建 - 所有 Range 对象都属于 Excel,您所得到的只是指向一个的指针),无论指针来自何处,都会影响 Range实例状态。

因此,如果您不想影响任何工作表,请不要影响任何 Rangework with arrays instead .

关于excel - 函数更改工作表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57611311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com