簡體   English   中英

Excel VBA:子可以使用未分配的參數調用UDF嗎?

[英]Excel VBA: Can a sub call a UDF with unassigned arguments?

我編寫了一個Excel模塊,將緯度/經度轉換為UTM坐標。 主要過程是定義參數並調用該函數的子程序,該函數又調用DLL函數。 想法是該函數打開函數參數窗口供用戶提供數據(函數在Application.MacroOptions的另一個子集中定義)。

Sub GeoToTM()

'Declare variables
Dim TM() As Variant
Dim Lat As Double
Dim Lon As Double
Dim TMProj As Integer
Dim Ellipsoid As Integer

'Call Excel function

TM = GeoConv(Lat, Lon, TMProj, Ellipsoid)

End Sub

'VBA function wrapper
Function GeoConv(Lat, Lon, TMProj, Ellipsoid) As Variant

Dim East As Double
Dim North As Double
Dim locTM(1 To 2) As Variant

'Call C++ function
GeodeticToTM Lat, Lon, TMProj, Ellipsoid, East, North

locTM(1) = East: locTM(2) = North
GeoConv = locTM

End Function

該函數本身按廣告執行,但是當我運行整個模塊時,可以訪問該函數,但不會出現函數參數窗口; 參數從不填充,因此函數返回零。

我該如何工作? “選項”參數是否有用?

謝謝,

克里斯

您應該能夠將可選值作為默認值傳遞給永遠不會使用的參數。 如果值是那些“不可能的”值,則用輸入框重寫。

Sub GeoToTM()

    'Declare variables
    Dim s As String
    Dim TM() As Variant
    Dim Lat As Double
    Dim Lon As Double
    Dim TMProj As Integer
    Dim Ellipsoid As Integer

    'Call Excel function

    'with Lat and Lon as values then
    TM = GeoConv(TMProj, Ellipsoid, Lat, Lon)

    'with Lat and Lon unassigned
    TM = GeoConv(TMProj, Ellipsoid)

End Sub

'VBA function wrapper
Function GeoConv(TMProj As Integer, Ellipsoid As Integer, _
            Optional Lat As Double = -1, Optional Lon As Double = -1) As Variant

    Dim East As Double
    Dim North As Double
    Dim locTM(1 To 2) As Variant

    If Lat < 0 Then _
        Lat = CDbl(InputBox("Latitude: ", "Supply Latitude", "0.000"))
    If Lon < 0 Then _
        Lon = CDbl(InputBox("Latitude: ", "Supply Longtitude", "0.000"))

    'Call C++ function
    GeodeticToTM Lat, Lon, TMProj, Ellipsoid, East, North

    locTM(1) = East: locTM(2) = North
    GeoConv = locTM

End Function

好吧,這就是我的工作方式:

重新排列代碼,我...

  • 在主子句中聲明了“輸入”變量,
  • 選擇了單元格范圍
  • 使用Selection.FormulaArray將Excel公式置於范圍內,
  • 使用Application.Dialogs(xlDialogFunctionWizard).Show調用已經填充的功能向導,
  • 然后調用Excel函數。

因此,.Show允許用戶填充參數,然后將其傳遞給Excel函數/ DLL函數。

Sub GeoToTM()

'Declare variables
Dim TM() As Double
Dim Lat As Double
Dim Lon As Double
Dim TMProj As Integer
Dim Ellipsoid As Integer

Dim resultRng As Range
Dim Arg As Boolean

'Initialize Cells
ActiveCell.Offset(-1, 0).Value = "Easting"
ActiveCell.Offset(-1, 1).Value = "Northing"

'Call Excel function
Set resultRng = Range(ActiveCell, ActiveCell.Offset(0, 1))
resultRng.Select
Selection.FormulaArray = "= GeoConv()"
Arg = Application.Dialogs(xlDialogFunctionWizard).Show
If Arg = False Then Exit Sub

TM = GeoConv(Lat, Lon, TMProj, Ellipsoid)

End Sub

實際上,我實際上必須從函數的參數中刪除“ Option”,這樣可以正常工作,但確實可以!

克里斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM