我有函数返回当前工作表的列表:
Function getListOfSheetsW() As Variant
Dim i As Integer
Dim sheetNames() As Variant
ReDim sheetNames(1 To Sheets.Count)
For i = 1 To Sheets.Count
sheetNames(i) = Sheets(i).name
Next i
getListOfSheetsW = sheetNames
End Function
然后我的函数返回TRUE或FALSE,具体取决于needle
是否在haystack
。
Function IsInArray2(ByVal needle As String, haystack() As String) As Boolean
Dim element As Variant
For Each element In haystack
If element = needle Then
IsInArray = True
Exit Function
End If
Next element
IsInArray = False
End Function
我的目标是创建新的子程序,首先检查具有给定名称的工作表是否已经存在,如果没有,则创建新工作表。我试过以下:
Sub CreateNewSheet(ByVal dstWSheetName As String)
Dim srcWSheetName As String
' Dim sheetNames() As String
Dim sheetNames() As Variant
sheetNames = getListOfSheetsW()
Dim sheetCount As Integer
If IsInArray2(dstWSheetName, sheetNames) Then
MsgBox "Sheet with following name: " & dstWSheetName & " already exists"
Else
srcWSheetName = ActiveSheet.name
sheetCount = Sheets.Count
' CREATE NEW SHEET
' Worksheets(dstWsheetName).Delete
Sheets.Add.name = dstWSheetName
' Q: why 6 instead of 5
' Worksheets("Test").Move after:=Worksheets("Sheet5")
Worksheets(dstWSheetName).Move After:=Worksheets(sheetCount + 1)
' SWITCH TO SRC SHEET
Worksheets(srcWSheetName).Activate
End If
End Sub
我这样称呼它:
Sub CallCreateNewSheet()
Call CreateNewSheet("test")
End Sub
我想问题出在Dim sheetNames() As String
或Dim sheetNames() As Variant
。
当我使用Dim sheetNames() As String
时,我得到了
运行时错误'13':类型不匹配
当我使用Dim sheetNames() As Variant
时,我得到:
编译错误:类型不匹配:数组或用户定义的预期类型
我有类似问题before,但定义sheetNames
因为数组在这里没有帮助。问题是什么?两个不同的错误是什么意思?
答案 0 :(得分:1)
如果从类型化数组切换到变体数组,您将避免所有这些问题。
在第一个功能中,删除以下行:
Dim sheetNames() As Variant
更改第二个功能的定义行:
Function IsInArray2(ByVal needle As String, haystack() As String) As Boolean
......对此:
Function IsInArray2(ByVal needle As String, haystack) As Boolean
在您的子网站中,更改此行:
Dim sheetNames() As Variant
......对此:
Dim sheetNames
答案 1 :(得分:1)
新脚本如何:
Sub NewSheetByName(SName as String)
Dim oldSheet as Object
For Each oldSheed in ThisWorkbook.Sheets
if oldSheet.Name = Sname Then
MsgBox "Sheet with following name: " & SName & " already exists"
Exit Sub
End If
Next
oldSheet = ActiveSheet
Sheets.Add.Name = SName
ActiveSheet.Move , Worksheets(Sheets.Count)
oldSheet.Activate
End Sub
答案 2 :(得分:1)
变量必须是sinc。
在两个过程中以相同的方式声明变量sheetNames
:
Sub CreateNewSheet(ByVal dstWSheetName As String)
和
Function getListOfSheetsW() As Variant
将其声明为:Dim sheetNames() As String
另请注意,Function IsInArray2
始终返回False
。
要更正此问题,请在函数正文中将IsInArray
替换为IsInArray2
。
总是拥有
是一个好习惯 Option Explicit
在模块的开头。
然而,它会省去验证工作表是否存在的所有麻烦,只是为了将目标工作表分配给变量,它会产生错误,如果工作表不存在,变量将不返回任何内容。试试这个:
Dim Wsh As Worksheet
On Error Resume Next
Set Wsh = Workbook(x).Worksheets("Test")
On Error GoTo 0
If Wsh Is Nothing Then Add Worksheet