简体   繁体   English

将存储在Excel单元格中的文本转换为VBA中的公式

[英]Converting text stored in Excel cell to a formula in VBA

I'm not sure if something like this is possible I've been told by co-workers that it can't because of the nature of strings versus formulas. 我不确定同事是否曾告诉我这样的事情是否可能,因为字符串和公式的性质是不可能的。 I would like to take the string: 我想把字符串:

'"=" & ValRange.offset(0,0).address

With a range declared in my VBA routine and convert is to a formula. 在我的VBA例程中声明一个范围,并将convert转换为公式。 In my routine I have the following code: 在我的例程中,我有以下代码:

Sub GetRange()
Dim strSource As String
Dim HomeRange As Range
Dim ValRange As Range

Set ValRange = Range("k1")
Set HomeRange = Range("e6")

strSouce = HomeRange.Value
strSource = Replace(strSource, """", "")
Range("e7") = strSource

End Sub

As you can see I've tried stripping characters but it does not seem to work (I understand as the code currently is that it would strip all quotes but just wanted to use as example. Any thoughts on converting this to a formula is appreciated. Matt 如您所见,我已经尝试过剥离字符,但似乎不起作用(据我了解,当前的代码是,它将剥离所有引号,但只想用作示例。将其转换为公式的任何想法都值得赞赏。马特

Let's say you ValRange is defined as cell A1. 假设您将ValRange定义为单元格A1。 In cell A2, you have your row offset value (say 0), and in cell A3 you have your column offset value (say 2). 在单元格A2中,您具有行偏移值(例如0),在单元格A3中,您具有列偏移值(例如2)。 In cell A4, enter =ADDRESS(ROW(OFFSET(A1,A2,A3)), COLUMN(OFFSET(A1,A2,A3))) You'll get $C$1 in cell A4 as your value. 在单元格A4中,输入=ADDRESS(ROW(OFFSET(A1,A2,A3)), COLUMN(OFFSET(A1,A2,A3)))您将在单元格A4中获得$ C $ 1作为您的值。

So, the 2 offsets give you a cell that is the appropriate offset you want. 因此,这两个偏移量为您提供了一个所需的适当偏移量的单元格。 Then you take the row, and column of that cell and send it to the address function to get your address. 然后,获取该单元格的行和列,并将其发送到地址函数以获取地址。

To convert that address back to the value in the offset cell, use =INDIRECT(A4) . 要将地址转换回偏移量单元格中的值,请使用=INDIRECT(A4) This will give you the value of whatever is in cell C1. 这将为您提供单元格C1中任何值的值。

Of course, you can just take these functions and call them from VB code if you'd prefer. 当然,您可以随意使用这些功能,并从VB代码中调用它们。

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

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