我是vba的新手所以请原谅我的无知。我创建了一个宏,它将通过下拉列表运行并打印下拉列表中的每个名称 - 它可以工作:
Sub PrintAll()
Dim Cell As Range
Dim Rng As Range
Dim Wks As Worksheet
Set Wks = Worksheets("PRINT PAGE")
Set Rng = ThisWorkbook.Names("Brokers").RefersToRange
For Each Cell In Rng
If Cell <> "" Then
Wks.Range("$B$5").Value = Cell.Text
Wks.PrintOut
End If
Next Cell
End Sub
但是,工作簿有多个工作表可供阅读,因此我需要vba从多个范围读取所以我试过这个
Sub PrintAll()
Dim Cell As Range
Dim Cell2 As Range
Dim Rng As Range
Dim Wks As Worksheet
Set Wks = Worksheets("PRINT PAGE")
If "$A$5" = "Company1" Then Rng = ThisWorkbook.Names("1Brokers").RefersToRange
ElseIf "$A$5" = "Company2" Then Rng = ThisWorkbook.Names("2Brokers").RefersToRange
Else: Set Rng = ThisWorkbook.Names("3Brokers").RefersToRange
End If
For Each Cell In Rng
If Cell <> "" Then
Wks.Range("$B$5").Value = Cell.Text
Wks.PrintOut
End If
Next Cell
End Sub
问题是我在If语句中继续“不使用If编译错误”。我是如何设置If语句或我在代码中使用它的方式有问题吗?
答案 0 :(得分:2)
这个块为我编译。请测试一下。我始终在then
中的if
之后开始设置。
Sub PrintAll()
Dim Cell As Range
Dim Cell2 As Range
Dim Rng As Range
Dim Wks As Worksheet
'Set Wks = Worksheets("PRINT PAGE")
If "$A$5" = "Company1" Then
Rng = ThisWorkbook.Names("1Brokers").RefersToRange
ElseIf "$A$5" = "Company2" Then
Rng = ThisWorkbook.Names("2Brokers").RefersToRange
Else
Set Rng = ThisWorkbook.Names("3Brokers").RefersToRange
End If
For Each Cell In Rng
If Cell <> "" Then
Wks.Range("$B$5").Value = Cell.Text
Wks.PrintOut
End If
Next Cell
End Sub
答案 1 :(得分:1)
使用
If Range("$A$5").Value = "Company1"..
同样为“$ A $ 5”。
“$ A $ 5”只是一个字符串,您将字符串与字符串进行比较。你想要的是一个范围对象
修改强>
关于您获得的错误,您必须使用Then
语法是(Hiten004帖子让我意识到它)
If <Cond> Then
ElseIF <Cond> Then
End If
答案 2 :(得分:0)
而不是:
If "$A$5" = "Company1" Then Rng = ThisWorkbook.Names("1Brokers").RefersToRange
使用:
If "$A$5" = "Company1" Then Set Rng = ThisWorkbook.Names("1Brokers").RefersToRange
您的代码中可能存在其他问题。