2016-07-01 58 views
0

功能工作並獲得屏幕分辨率。但是,當我嘗試傳遞給子fun_x和fun_y回來空。爲什麼?功能不返回屏幕Res值

Private Sub Form_Open(Cancel As Integer) 

Dim sub_x As Long, sub_y As Long 

ScreenRes fun_x:=sub_x, fun_y:=sub_y 

Debug.Print sub_x, sub_y, fun_x, fun_y 

End Sub 

模塊名稱:MOD_GET_RES

Option Compare Database 

Declare Function GetSystemMetrics32 Lib "User32" _ 
Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long 

Function ScreenRes(ByVal fun_x As Long, ByVal fun_y As Long) 

fun_x = GetSystemMetrics32(0) ' width in points 
fun_y = GetSystemMetrics32(1) ' height in points 

End Function 

回答

2

您已經通過函數的參數ByVal(UE),所以當它返回,只有一個拷貝被修改。使用ByRef(erence)隱含或不使其工作:

Function ScreenRes(fun_x As Long, fun_y As Long) 

你也可以將GetSystemMetrics32私人(你爲什麼要使用更長的別名?)。

編輯:下面是一個最小的例子一些更多的解釋。

Option Explicit 

Sub CantChange(ByVal a As Integer, ByVal b As Integer) 
    'When this gets called, a copy of the original variables 
    'is pushed on the stack. 
    a = a * 2 'The copy is altered. 
    b = b + 1 
    'When leaving this Sub, the copy is discarded. 
End Sub 

'exactly the same Sub procedure... except for the (implicit) ByRef 
Sub Change(a As Integer, b As Integer) 
    'When this gets called, references 
    '(i.e. the location of the original variable) 
    'are pushed on the stack. 
    a = a * 2 'The original variable is altered. 
    b = b + 1 
End Sub 

Sub Test() 
    Dim a As Integer, b As Integer 
    a = 1 
    b = 5 
    Debug.Print "before:", a, b 
    CantChange a, b 
    Debug.Print "unchanged:", a, b 
    Change a, b 
    Debug.Print "changed:", a, b 
End Sub 
+0

這工作,但我不明白爲什麼。我想我需要做一些閱讀差異。 – Kaw4Life

+0

我已經添加了一個簡單的例子,我希望它現在更清晰;) – guihuy

+0

謝謝你花時間把它們放在一起。非常有助於理解爲什麼而不是如何。 – Kaw4Life