设置一个string/单元格内容的范围
我正在写一些客户端的代码,从许多不同的布局文件中提取数据。 我想写一些对他来说相当灵活的东西。
因此,他将能够在单元格中写入例如y.offset(0,1)
,这取决于数据将在哪里与variablesy
相关。
我之所以不把variables1
作为原因,是因为它和单元格可能包含或可能不包含多个“blah blah”
基本上,我想知道是否有可能在单元中编写代码的一部分,然后把它们合并到代码中。
例如:
Dim y as range Dim x as range Dim c as string Set Y = Sheet1.range("G4") c = sheet1.range("A1") [which contains the words y.offset(0,4) Set x = c
这不起作用,但我想知道是否有什么可以做到获得相同的结果。
你的需求是一种recursion的和危险的
那么它值得这样一个recursion的和危险的答案
您可以使用VBA项目对象模型(请参阅此处了解信息),并按以下方式操作:
-
设置你的项目来处理VBA对象模型
请按照上面给出的链接到cpearson网站的介绍添加对您的项目的引用中可以看到的所有步骤
免责声明:请仔细阅读那里的注意事项
-
添加“帮手”模块
添加到您的项目一个新的模块,并称之为“HelperModule”后(你可以调用它,只要你喜欢,但是与所选的名称一致)
然后将这个代码添加到这个新的模块
Function GetRange(refRng As Range) As Range Set GetRange = refRng End Function Function SetToCellContent(refRng As Range, cellContent As String) As Range UpdateCodeModule cellContent Set SetToCellContent = HelpModule.GetRange(refRng) End Function Sub UpdateCodeModule(cellContent As String) Dim CodeMod As VBIDE.CodeModule Dim LineNum As Long Set CodeMod = ActiveWorkbook.VBProject.VBComponents("HelperModule").CodeModule LineNum = SearchCodeModuleLine(CodeMod, "Set GetRange") CodeMod.ReplaceLine LineNum, " Set GetRange = " & cellContent End Sub Function SearchCodeModuleLine(CodeMod As VBIDE.CodeModule, FindWhat As String) As Long Dim SL As Long ' start line Dim SC As Long ' start column Dim EL As Long ' end line Dim EC As Long ' end column Dim Found As Boolean With CodeMod SL = 1 EL = .CountOfLines SC = 1 EC = 255 Found = .Find(Target:=FindWhat, StartLine:=SL, StartColumn:=SC, EndLine:=EL, EndColumn:=EC, wholeword:=True, MatchCase:=False, patternsearch:=False) End With SearchCodeModuleLine = SL End Function
-
将此代码添加到您的主代码
Set x = SetToCellContent(y, c) '<--| call the function that will take care of updating code in 'GetRange()' function and returns a range relative to 'y' as per the "code" in 'c'