2016-07-01 1 views
0

関数は機能し、画面解像度を取得します。しかし、私がsub 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 

モジュール名:あなたは関数の引数ByVal(UE)を通過してきた

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

それが返すときMOD_GET_RESので、唯一のコピーが変更されます。それを動作させるために、暗黙的かをByRef(レンス)を使用します。

Function ScreenRes(fun_x As Long, fun_y As Long) 

あなたはまた、GetSystemMetrics32(なぜあなたは長いエイリアスを使用していますか?)プライベート作ることができます。

EDIT:以下は、最小限の例の説明です。

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

それをまとめる時間をとっていただきありがとうございます。方法よりもむしろWHYを理解するのに非常に役立ちます。 – Kaw4Life