简体   繁体   English

Excel VBA:动态变量名称

[英]Excel VBA: Dynamic Variable Name

Note: I am limited to PHP <-> VBA.注意:我仅限于 PHP <-> VBA。 Please do not suggest anything that requires an Excel Addon, or any other language/method.请不要建议任何需要 Excel 插件或任何其他语言/方法的内容。

I have a function that connect to a specified URL, submits data, and then retrieves other data.我有一个函数可以连接到指定的 URL,提交数据,然后检索其他数据。 This works great.这很好用。 I'm trying to write it so i can use it as a generic function I can use to connect to any file I need to connect to - each would return different data (one could be user data, one could be complex calculations etc).我正在尝试编写它,以便我可以将它用作通用函数,我可以使用它来连接到我需要连接的任何文件 - 每个文件都会返回不同的数据(一个可能是用户数据,一个可能是复杂的计算等)。

When it retrieves the data from PHP, is there a way to dynamically set the variables based on what is received - even if i do not know what has been received.当它从 PHP 检索数据时,有没有办法根据收到的内容动态设置变量 - 即使我不知道收到了什么。

I can make PHP return to VBA the string in any format, so I'm using the below as an example:我可以让 PHP 以任何格式将字符串返回给 VBA,因此我使用下面的示例:

String that is received in vba:在 vba 中收到的字符串:

myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday

If i were to parse this in PHP, I could do something similar to (not accurate, just written for example purposes);如果我要在 PHP 中解析它,我可以做类似的事情(不准确,只是为了示例目的而写的);

$myData = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
$myArr = explode("&",$myData)
foreach($myArr as $key => $value){
    ${$key} = $value;
}
echo $someOtherValue; //Would output to the screen 'Hockey';

I would like to do something similar in VBA.我想在 VBA 中做类似的事情。 The string I am receiving is from a PHP file, so I can format it any way (json etc etc), I just essentially want to be able to define the VARIABLES when outputting the string from PHP.我收到的字符串来自 PHP 文件,因此我可以以任何方式对其进行格式化(json 等),我只是希望能够在从 PHP 输出字符串时定义 VARIABLES。 Is this possible in VBA?.这在 VBA 中可能吗?

The current state of the function I have that is working great for connections is as below:-我所拥有的对连接非常有用的功能的当前状态如下:-

Function kick_connect(url As String, formdata)

'On Error GoTo connectError
Dim http
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "POST", url, False
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

http.send (formdata)
kick_connect = http.responseText
Exit Function

connectError:
kick_connect = False

End Function

Ultimately, I want to be able to do something like最终,我希望能够做类似的事情

sub mySub
    myData = "getId=" & Range("A1").Value
    myValue = kick_connect("http://path-to-my-php-file.php",myData)
    if myValue = False then
        'Handle connection error here
        exit sub
    end if

    'do something snazzy here to split "myValue" string (eg "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday") into own variables

    msgbox(myValue1) 'Should output "Dave"


end sub

Obviously I could put the values into an array, and reference that, however I specifically want to know if this exact thing is possible, to allow for flexibility with the scripts that already exist.显然,我可以将这些值放入一个数组中,并引用它,但是我特别想知道这是否可能,以便灵活地处理已经存在的脚本。

I hope this makes sense, and am really grateful for any replies i get.我希望这是有道理的,非常感谢我得到的任何答复。

Thank you.谢谢你。

You can use a Collection:您可以使用集合:

Dim Tmp As String
Dim s As String
Dim i As Integer
Dim colVariabili As New Collection

Tmp = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"

Dim FieldStr() As String
Dim FieldSplitStr() As String
FieldStr = Split(Tmp, "&")

For Each xx In FieldStr
    FieldSplitStr = Split(xx, "=")
    colVariabili.Add FieldSplitStr(1), FieldSplitStr(0)
Next

Debug.Print colVariabili("myValue1")
Debug.Print colVariabili("someOtherValue")
Debug.Print colVariabili("HockeyDate")

It's ok if you don't have the correct sequence of var...如果您没有正确的 var 序列也没关系...

I am not sure if this can help you, but as far as I understand your question you want to be able to create the variables dynamically based on the query string parameters.我不确定这是否可以帮助您,但据我了解您的问题,您希望能够根据查询字符串参数动态创建变量。 If so then here is example how to add this variables dynamically.如果是这样,那么这里是如何动态添加此变量的示例。 Code needs standard module with a name 'QueryStringVariables'.代码需要名为“QueryStringVariables”的标准模块。 In this module the query string will be parsed and each query string parameter will be added as get-property.在此模块中,将解析查询字符串,并将每个查询字符串参数添加为 get-property。 If you wish to be able to change the value as well then you will need to add let-property as well.如果您也希望能够更改该值,那么您还需要添加 let-property。

在此处输入图片说明

Add reference to Microsoft Visual Basic For Applications Extensibility添加对 Microsoft Visual Basic For Applications Extensibility 的引用

Option Explicit

Private Const SourceQueryString As String = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"

Sub Test()
    
    Dim queryStringVariablesComponent As VBIDE.vbComponent
    Dim queryStringVariablesModule As VBIDE.CodeModule
    Dim codeText As String
    Dim lineNum As Long: lineNum = 1
    Dim lineCount As Long
    
    Set queryStringVariablesComponent = ThisWorkbook.VBProject.VBComponents("QueryStringVariables")
    Set queryStringVariablesModule = queryStringVariablesComponent.CodeModule
    queryStringVariablesModule.DeleteLines 1, queryStringVariablesModule.CountOfLines
    
    Dim parts
    parts = Split(SourceQueryString, "&")

    Dim part, variableName, variableValue
    For Each part In parts
        variableName = Split(part, "=")(0)
        variableValue = Split(part, "=")(1)
        
        codeText = "Public Property Get " & variableName & "() As String"
        queryStringVariablesModule.InsertLines lineNum, codeText
        lineNum = lineNum + 1
        
        codeText = variableName & " = """ & variableValue & ""
        queryStringVariablesModule.InsertLines lineNum, codeText
        lineNum = lineNum + 1
        
        codeText = "End Property"
        queryStringVariablesModule.InsertLines lineNum, codeText
        lineNum = lineNum + 1
        
    Next
    
    DisplayIt
End Sub

Sub DisplayIt()
    MsgBox myValue1 'Should output "Dave"
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM