在弄清楚如何从另一个子目录中编辑子目录时遇到麻烦。我尝试过:
Sub Sub1()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet2")
ws.Range("A1").Value = "Useless"
End Sub
Sub Sub2()
Dim test as string
test = ThisWorkbook.Worksheets("Sheet1").Range("B3").Value
If test = "here" Then
Call Sub1
With Sub1
ws.Range("A2").Value = test.Value
End With
End If
我收到一个expected function or variable
错误,可能是由于Sub1
应该是一个函数。但是即使将其更改为函数,Sub2
仍然可以正常运行,尽管代码可以运行。
答案 0 :(得分:3)
当您尝试将Sub1
转换为函数时,实际上您处在正确的轨道上。您只需要使函数“返回”创建的工作表对象即可。在这里:
Function Sub1() As Worksheet ' Don't forget to use a different name for Sub1 (and
' preferably Sub2 as well).
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet2")
ws.Range("A1").Value = "Useless"
Set Sub1 = ws
End Function
Sub Sub2()
Dim test As String
test = ThisWorkbook.Worksheets("Sheet1").Range("B3").Value
If test = "here" Then
With Sub1
.Range("A2").Value = test
End With
End If
End Sub
很显然,您需要将Sub1
的名称更改为其他可以反映函数功能的名称。
另外,请注意,我使用test
而不是您的test.Value
,因为test
已经是一个字符串,并且没有Value
属性。
答案 1 :(得分:0)
Public ws As Worksheet
Sub Sub1()
Set ws = ThisWorkbook.Worksheets("Sheet2")
ws.Range("A1") = "Useless"
End Sub
Sub Sub2()
Dim test As String
test = ThisWorkbook.Worksheets("Sheet1").Range("B3")
If test = "here" Then
Sub1
ws.Range("A2") = test
End If
End Sub
答案 2 :(得分:0)
另一种方法是通过将变量作为参数传递:
python -m googlesamples.assistant.auth_helpers --client-secrets /path/to/file.json
或将Sub Sub1(ByRef ws As Worksheet) 'The variable is passed ByRef as default, but wanted to make it clear.
Set ws = ThisWorkbook.Worksheets("Sheet2")
ws.Range("A1") = "Useless" 'Value is the default property of Range.
End Sub
Sub Sub2()
Dim test As String
Dim wrkSht As Worksheet
test = ThisWorkbook.Worksheets("Sheet1").Range("B3")
If test = "here" Then
Sub1 wrkSht 'Pass the variable to Sub1 to get defined.
wrkSht.Range("A2") = test
End If
End Sub
变成返回对工作表的引用的函数:
Sub1