2015-12-15 86 views
4

我無法調用宏的名字我都存儲在一個字符串數組。呼叫多個宏使用數組和功能在Excel VBA中

附上的代碼。

Option Explicit 
Option Compare Text 

Dim i, Ro As Integer 

Public Sub Universal_Macro() 

Dim Col(10) As Integer 
Dim macro_name(10) As String 

Ro = ActiveCell.Row 

i = 1 

For i = 1 To 10 
    Call Mac_Sched(Col(), macro_name()) 
Next 

End Sub 

Sub Mac_Sched(Col() As Integer, Internal_Array() As String) 
    Cells(Ro, Col(i)).Select 
    Call Internal_Array(i) 
End Sub 

sub Mac_Sched中出現錯誤。

+1

你沒有資格'cells'或通過'i'。 – findwindow

+0

在這裏得到錯誤調用Internal_Array(i)它說預期的子或函數或屬性 –

+3

你不能''調用'一個字符串。試着看一下在'CallByName' –

回答

0

TBBH,我真不知道你想實現什麼和重編校代碼無助於顯示出比其他企圖具體方法在調用從數組元素衍生出的字符串的宏。

Application.OnTime method使用一個字符串作爲調用程序的名稱。

Option Explicit 
Option Compare Text 
Dim i As Integer, Ro As Integer 

Sub zero() 
    Debug.Print "zero: " & i 
End Sub 

Sub first() 
    Debug.Print "first: " & i 
End Sub 

Sub second() 
    Debug.Print "second: " & i 
End Sub 

Sub third() 
    Debug.Print "third: " & i 
End Sub 

Public Sub Universal_Macro() 
    Dim Col() As Integer 
    Dim macro_Name As Variant 


    macro_Name = Array("zero", "first", "second", "third") 
    ReDim Col(UBound(macro_Name)) 
    For i = LBound(macro_Name) To UBound(macro_Name) 
     Col(i) = i 
    Next 

    Ro = ActiveCell.Row 

    For i = LBound(macro_Name) To UBound(macro_Name) 
     Call macro_Sched(Col(i), macro_Name) 
    Next 

End Sub 

Sub macro_Sched(c As Integer, internal_Array As Variant) 
    Cells(Ro, c + 1).Select '<~~Don't rely on Select! You dont' even reference a worksheet here. 
    Application.OnTime Now, internal_Array(c) 
End Sub 

如果參數是要傳遞給孩子Sub過程,然後某種形式的字符串替換的可能適應這一點,但對孩子潛艇細節並非是顯而易見的。


How to avoid using Select in Excel VBA macros更多的方法從依靠選擇越來越遠,並激活,以實現自己的目標。

2

嘗試使用Application.Run

Sub RunMc() 

Dim a(1 To 2) As String 
Dim MN As String 

For i = 1 To 2 'Fill the array 
    a(i) = "m" & i 
Next 
MN = "Module1" 'the module name 

For i = LBound(a) To UBound(a) 
    Application.Run MN & "." & a(i) 
Next 

End Sub 

Sub m1() 
Debug.Print "m1" 
End Sub 

Sub m2() 
Debug.Print "m2" 
End Sub