VBA 将活动表的名称传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13788749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:44:40  来源:igfitidea点击:

VBA pass the name of activesheet to a function

excel-vbaexcel-2010vbaexcel

提问by Cimbian

I have created a function to receive three parameters.:

我创建了一个函数来接收三个参数。:

  • An array of strings
  • A worksheet name
  • An index for the array of strings
  • 字符串数组
  • 工作表名称
  • 字符串数组的索引

When I compile I am getting a compile error stating:

当我编译时,我收到一个编译错误,指出:

Compile Error: Expected:=

编译错误:预期:=

My call is:

我的电话是:

Sub C_Button_ImportBOM_Click()

  Dim strFilePathName As String
  Dim strFileLine As String
  Dim v As Variant
  Dim RowIndex As Long
  Dim mySheet As Worksheet

  ActiveSheet.Name = "Import"

  mySheet = Worksheets("Import")

  strFilePathName = ImportFilePicker

  v = QuickRead(strFilePathName)
  For RowIndex = 0 To UBound(v)
    PopulateNewLine (v(RowIndex), mySheet, RowIndex)
  Next

End Sub

The function declaration is:

函数声明是:

Function PopulateNewLine(SourceString As String, ImportSheet As Worksheet, CurrentRow As Long)

I have tried many things to no avail. Initially with just the first argument declared and used this worked okay.

我尝试了很多事情都无济于事。最初只声明第一个参数并使用它可以正常工作。

Any ideas greatly appreciated.

任何想法都非常感谢。

Excel 2010 VBA

Excel 2010 VBA

采纳答案by Doug Glancy

You are calling your function like a subroutine, i.e., you're not returning a value from it and assigning it to a variable, as you'd normally do with a function. That means you need to call it without the parentheses surrounding the arguments:

您像调用子程序一样调用您的函数,即您不会像通常使用函数那样从它返回一个值并将其分配给一个变量。这意味着您需要在参数周围不带括号的情况下调用它:

PopulateNewLine v(RowIndex), mySheet, RowIndex

If you really aren't returning anything from it, you should probably turn it into a Sub for clarity's sake:

如果您真的没有从中返回任何内容,为了清楚起见,您可能应该将其转换为 Sub :

Sub PopulateNewLine(SourceString As String, ImportSheet As Worksheet, CurrentRow As Long)
... your code here
End Sub

On another note, you should qualify your mySheet reference, and as I mentioned in the comments, use Set. It should look something like:

另一方面,你应该限定你的 mySheet 引用,正如我在评论中提到的,使用Set. 它应该看起来像:

Set mySheet = ActiveWorkbook.Worksheets("Import")

Substitute whatever workbook Import is in for ActiveWorkbookabove.

替换上面的任何工作簿导入ActiveWorkbook