我有一个简单的函数,用于对工作表中给定范围的每一行进行着色:
Public Function ShadeEveryOtherRow()
Sheets("mySheet").Select
ShadedRows = Range("myRange").Rows.Count
' determines the number of rows to shade in the range
' Code that loops through and shades rows here
End Function
我希望能够使用给定的工作表名称和范围作为输入来调用此函数。如果我按如下所示编写函数并尝试使用test()子函数执行,则会出现“编译错误:类型不匹配”错误。任何援助将不胜感激。感谢。
Public Function ShadeEveryOtherRow(targetSheet As Worksheet, targetRange As Range)
Dim targetSheet As Worksheet
Dim targetRange As Range
Sheets(targetSheet).Select
shadeRows = Range(targetRange).Rows.Count
'Code that shades rows here
End Function
Sub test()
ShadeEveryOtherRow "mySheet", "myRange"
End Sub
答案 0 :(得分:1)
targetRange
和targetSheet
应该是string类型,而不是作为对象传递给函数。
Public Function ShadeEveryOtherRow(targetSheet As string, targetRange As string)
Dim targetSheet As Worksheet
Dim targetRange As Range
Sheets(targetSheet).Select
shadeRows = Range(targetRange).Rows.Count
'Code that shades rows here
End Function
Sub test()
ShadeEveryOtherRow "mySheet", "myRange"
End Sub
答案 1 :(得分:1)
不要两次Dim
变量。在函数签名中声明它们就足够了。另外,请勿使用.Select
。做你想要明确做的事。
Public Function ShadeEveryOtherRow(targetSheet As string, targetRange As string)
shadeRows = Sheets(targetSheet).Range(targetRange).Rows.Count
'Code that shades rows here
End Function
编辑: 就像Sigil指出的那样,你应该为你的变量使用字符串。另一种选择是明确传递范围。
Public Function ShadeEveryOtherRow(targetRange As Range)
shadeRows = targetRange.Rows.Count
'Code that shades rows here
End Function
Sub test()
ShadeEveryOtherRow Sheets("mySheet").Range("myRange")
End Sub
请记住!始终在所有代码的顶部使用Option Explicit
。