我需要有关如何保留在“私有子”中分配的变量值并将其传递到“主子”中的建议
代码如下:
Global DocDate as String
Sub Main()
```(some code before)```
Call RemitterParsing
```this goes for 8 different values```
Set objDocDate = objDoc.createElement("PayerDocumentDa")
objRemitt.appendChild objDocDate
objDocDate.Text = DocDate
End Sub
Private Sub RemitterParsing()
OpenPosition = InStr(Range(foundRmt.Address).Offset(2, 0).Value, "PayerDocumentDa>")
closeposition = InStr(Range(foundRmt.Address).Offset(2, 0).Value, "</PayerDocumentDa")
DocDate = Mid(Range(foundRmt.Address).Offset(2, 0).Value, OpenPosition + 16, closeposition - OpenPosition - 16)
End Sub
这就是为什么我想调用另一个子对象一次获得所有8个值,然后在主子对象中使用它们。函数会调用它们8次。
答案 0 :(得分:2)
您的代码按原样工作。
但是我建议不要使用Public
变量,除非必要,并在子之间传递变量,如下所示:
Option Explicit
Sub Main()
Dim var1 As String ' declare a variable in scope with Main sub
assignValue var1 ' call 'assignValue' sub passing it the variable to be set
MsgBox var1 ' see variable has been set
End Sub
Private Sub assignValue(var1 As String) ' have the sub accept a variable as argument
var1 = "Hello" ' set the passed variable
End Sub
答案 1 :(得分:0)
对不起,大家,我的方法行得通,但是我发现了一个错误。我在main子目录中再次将该值声明为“ Dim”。删除它并起作用
答案 2 :(得分:0)
如果我正确地阅读了该注释(“这是我的原始代码需要返回8个不同的值...”),则可能需要尝试使用User Definded Type(UDT,通常称为如Structure
的其他语言):
' Define the UDT in the General section of a module
Type MyReturnValues
' Expand the individual UDT members as needed
Value1 As String
Value2 As Long
Value3 As Date
' ... More members, if needed
DocDate As String
End Type
Sub Main()
Dim udtReturn As MyReturnValues
' ```(some code before)```
udtReturn = RemitterParsing()
' Show the results of RemitterParsing()
With udtReturn
Debug.Print "Value1: "; .Value1, "Value2: "; .Value2, "Value3: "; .Value3, "DocDate: "; .DocDate
End With
' ```this goes for 8 different values```
Set objDocDate = objDoc.createElement("PayerDocumentDa")
objRemitt.appendChild objDocDate
objDocDate.Text = DocDate
End Sub
Private Function RemitterParsing() As MyReturnValues
Dim udt As MyReturnValues
OpenPosition = InStr(Range(foundRmt.Address).Offset(2, 0).Value, "PayerDocumentDa>")
closeposition = InStr(Range(foundRmt.Address).Offset(2, 0).Value, "</PayerDocumentDa")
udt.DocDate = Mid(Range(foundRmt.Address).Offset(2, 0).Value, OpenPosition + 16, closeposition - OpenPosition - 16)
' Populate a 2nd UDT member
OpenPosition2 = InStr(Range(foundRmt.Address).Offset(2, 0).Value, "PayerDocumentDa>")
closeposition2 = InStr(Range(foundRmt.Address).Offset(2, 0).Value, "</PayerDocumentDa")
udt.Value1 = Mid(Range(foundRmt.Address).Offset(2, 0).Value, OpenPosition + 16, closeposition - OpenPosition - 16)
' Add random stuff for demonstration
With udt
.Value2 = 123
.Value3 = Now()
End With
' Return the values
RemitterParsing = udt
End Function