[英]VBA: Using a concatenated string as a command
How can you you use a concatenated string as a command in VBA?您如何在 VBA 中使用连接字符串作为命令? The following code results in the following error:
以下代码导致以下错误:
Run-time error 424: Object required
运行时错误 424:需要 Object
Sub run()
Dim pic As Picture
Dim wks As Worksheet
Set wks = Sheets("Counter Party Select")
wks.Unprotect
Dim company As String
Dim sRange As String
Dim concate As String
Dim quote As String
Dim s1 As String
company = wks.Range("B3")
'This vlookup pulls the correct range based on the value
sRange = Application.VLookup(company, Sheets("Company Logos").Range("D3:E1000"), 2)
s1 = "Company Logos"
quote = Chr$(34) 'The character number of a quatation mark
Concat = "Sheets(" & quote & s1 & quote & ")." & sRange
'This results in Concat = "Sheets("Company Logos").Range("A146:A148")"
Concat.Copy 'The error occurs on this line
wks.Select
wks.Range("D2").Select
ActiveSheet.Paste
wks.Range("A1").Select
End Sub
How can I rewrite this code so that I can make the string an object and execute the .Copy
command on it?如何重写此代码,以便将字符串设为 object 并对其执行
.Copy
命令?
You cannot use a concatenated string as a full-fledged VBA statement.您不能将连接字符串用作成熟的 VBA 语句。 You can however easily concatenate a range address.
但是,您可以轻松地连接范围地址。
You cannot do that straight away because you have made your life more complicated by storing wrong data:你不能马上这样做,因为你通过存储错误的数据使你的生活变得更加复杂:
'This results in Concat = "Sheets("Company Logos").Range("A146:A148")"
You should not store the literal text Range("A146:A148")
in that second column that you VLookup
.您不应将文字文本
Range("A146:A148")
存储在VLookup
的第二列中。 You should only store the address itself, A146:A148
, as text.您应该只将地址本身
A146:A148
存储为文本。
Fix the data on the sheet accordingly, and it will work as expected:相应地修复工作表上的数据,它将按预期工作:
Dim Concat As Range
Set Concat = Sheets(s1).Range(sRange)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.