简体   繁体   English

在 Visual Basic 中将字符串文本用作 Excel 的代码

[英]Use String text as Code in Visual Basic for Excel

For various reasons, I need to concatenate a text of the form [NAME].Value by changing the value of NAME to an inputbox entry.由于各种原因,我需要通过将NAME的值更改为输入框条目来连接[NAME].Value形式的文本。

Something like this:像这样的东西:

Sub example()

      data_in = InputBox("Give me something: ")
 
      mystring1 = "[" & data_in & "].Value"
 
      a = Evaluate(mystring1) 'I know this is wrong, but I don't know how to do so.

End Sub

I know it can be done in other ways, and the example in which I want to use this code is not exactly this one, and while it can be done in several ways here, in the original code it can only be done this way.我知道它可以通过其他方式完成,而我想要使用此代码的示例并不完全是这个,虽然在这里可以通过多种方式完成,但在原始代码中只能这样完成。

I want, based on the input in the imputbox, to concatenate the string in whatever way, and subsequently cast that string as code to store the value in another variable, to be used later in the code.我希望根据输入框中的输入以任何方式连接字符串,然后将该字符串转换为代码以将值存储在另一个变量中,以便稍后在代码中使用。

I am not able to get VBA to read the string text as code.我无法让 VBA 将字符串文本作为代码读取。 I have seen that there is a way that consists of creating a macro from this first macro, execute it, and then delete the recently created macro.我已经看到有一种方法包括从第一个宏创建一个宏,执行它,然后删除最近创建的宏。 The problem with this solution is that doing that I can't save the variable when returning to the initial macro (I don't want to use global variables).这个解决方案的问题在于,这样做我在返回初始宏时无法保存变量(我不想使用全局变量)。

Surely there must be a way?一定有办法吗?

Thank you very much.非常感谢。

EDIT: The code above returns Error 2015编辑:上面的代码返回错误 2015

In order to use a string as if it was code, you can use the evaluate function (exists in most languages)为了像使用代码一样使用字符串,您可以使用评估 function(存在于大多数语言中)

The official documentation mentions this example: 官方文档中提到了这个例子:

[a1].Value = 25 
Evaluate("A1").Value = 25 
 
trigVariable = [SIN(45)] 
trigVariable = Evaluate("SIN(45)") 
 
Set firstCellInSheet = Workbooks("BOOK1.XLS").Sheets(4).[A1] 
Set firstCellInSheet = _ 
    Workbooks("BOOK1.XLS").Sheets(4).Evaluate("A1")

I have figured out the easiest way to do it, sorry for posting the question so soon.我已经找到了最简单的方法,很抱歉这么快就发布问题。

Thanks to @Andreas for the solution.感谢@Andreas 的解决方案。 I'll write it here in case than could be useful to someone.我会在这里写下来,以防对某人有用。

Sub example()

      data_in = InputBox("Give me something: ")
 
      a = Range(data_in).Value
 
      Debug.Print a

End Sub

In the end the simplest thing is the last thing you try...最后,最简单的事情是你尝试的最后一件事......

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

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