gpt4 book ai didi

VBA:编写 CopyAndPaste 函数

转载 作者:行者123 更新时间:2023-12-04 21:15:51 25 4
gpt4 key购买 nike

我写了一个CopyAndPaste函数并尝试从 Main 调用该函数.但是,在以下位置出现错误:

CopyAndPaste(ThisWS,FromRange,ThisWS,ToRange,False)

Compile Error
Expected: =



我可以知道为什么会这样吗?
Sub Main()

Dim ThisWS As Worksheet, FromRange As Range, ToRange As Range

Set ThisWS = ActiveSheet
Set FromRange = Range("I6")
Set ToRange = Range("M6")

CopyAndPaste(ThisWS,FromRange,ThisWS,ToRange,False)

End Sub


Function CopyAndPaste(RefSheet As Worksheet, RefRange As Range, ToSheet As Worksheet, ToRange As Range, _
Optional HLink As Boolean)

RefSheet.RefRange.Copy Destination:=ToSheet.ToRange

If HLink = True Then
ActiveSheet.Hyperlinks.Add _
Anchor:=ToSheet.ToRange, _
Address:="", _
SubAddress:=RefSheet.Name & "!" & RefRange.Address, _
ScreenTip:="Click to view details", _
TextToDisplay:=""
End If

End Function

最佳答案

其他答案似乎将括号视为仅仅是装饰细节。他们不是。
我无法重现您的确切编译错误,但您的代码无效。这是 Minimal, Complete, Verifiable Example这解释了发生了什么:
有效代码

Option Explicit

Public Sub DoSomething()
Test Nothing
End Sub

Function Test(foo As Object)
End Function
无效的代码
Option Explicit

Public Sub DoSomething()
Test (Nothing) ' compile error: invalid use of object
End Sub

Function Test(foo As Object)
End Function
唯一的区别是括号。那么这些括号究竟是做什么的呢?

This is confusing, why not just use parentheses?

Parentheses force VBA to evaluate the value of the bracketed expression, and pass the result ByVal to the called procedure.


括号基本上意味着“将此表达式评估为一个值” - 我们正在尝试使用在编译时已知的对象引用来做到这一点:VBA拒绝继续,并提示。
使用多个参数更加明显 - VBA 应该将此表达式评估为什么?
(Sheet1, Thisworkbook, Nothing)
  • 调用 Sub 时过程中,绝对不能提供括号。
  • 调用 Function 时过程中,只要不丢弃函数的返回值,就必须提供括号。

  • 换句话说,不禁止拥有 Function Sub 的程序过程语义(即没有返回值,副作用)。
    语义正确的代码
    Option Explicit

    Public Sub DoSomething()
    Debug.Print Test(Nothing) 'parentheses required because we're using the returned value
    End Sub

    Function Test(foo As Object) As String
    'compute something using foo, return a value
    End Function

    关于VBA:编写 CopyAndPaste 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381512/

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