我正在使用Michael Alexander和John Walkenbach撰写的101个Ready-to_use宏中的代码。
在此代码中,它们指定代码中的范围值。我希望用户能够选择值。在我成功让用户输入范围值后,我收到错误。为了帮助我调试问题,我刚刚编写了一个简短的宏来测试我正在尝试做什么。但我似乎无法将信息传递到消息框,所以我可以看到它正在工作(虽然看起来,当用户选择地址显示在输入框中的范围时。)我无法弄清楚如何获取用户提供的RANGE类型并将其转换为STRING值以显示在我的消息中或将其用作范围。现在作为一个新手,我现在认为这个小测试比原始问题更重要,以帮助学习调试。
(我尝试了一些不同的变体,包括将AS RANGE作为AS Variant并尝试使StringVariable分配RANGE的值(例如UserRange = Rng1其中UserRange是String类型而Rng1是类型Range):
这是我的代码
Sub SelectRange()
Dim Rng1 As Range
Set Rng1 = Application.InputBox("select cell", Type:=8)
MsgBox ("You selected " & Rng1 & "as the range")
End Sub
以下是原始代码:
Sub Macro101()
' I've already changed Step#4 to read the worksheet name instead of C20
' I'm now trying to change Step#3 to let the user select the range but
' I'm having problems using the input from the user becuase I've made that
' Variable as Range (Not shown here).
'Step 1: Declare your variables
Dim pp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim PPSlide As PowerPoint.Slide
Dim xlwksht As Excel.Worksheet
Dim MyRange As String
Dim MyTitle As String
Dim Slidecount As Long
'Step 2: Open PowerPoint, add a new presentation and make visible
Set pp = New PowerPoint.Application
Set PPPres = pp.Presentations.Add
pp.Visible = True
'Step 3: Set the ranges for your data and title
MyRange = "A1:J29"
'Step 4: Start the loop through each worksheet
For Each xlwksht In ActiveWorkbook.Worksheets
xlwksht.Select
Application.Wait (Now + TimeValue("0:00:1"))
MyTitle = xlwksht.Range("C20").Value
'Step 5: Copy the range as picture
xlwksht.Range(MyRange).CopyPicture _
Appearance:=xlScreen, Format:=xlPicture
'Step 6: Count slides and add new slide as next available slide number
Slidecount = PPPres.Slides.Count
Set PPSlide = PPPres.Slides.Add(Slidecount + 1, ppLayoutTitleOnly)
PPSlide.Select
'Step 7: Paste the picture and adjust its position
PPSlide.Shapes.Paste.Select
pp.ActiveWindow.Selection.ShapeRange.Align msoAlignCenters, True
pp.ActiveWindow.Selection.ShapeRange.Top = 100
'Step 8: Add the title to the slide then move to next worksheet
PPSlide.Shapes.Title.TextFrame.TextRange.Text = MyTitle
Next xlwksht
'Step 9: Memory Cleanup
pp.Activate
Set PPSlide = Nothing
Set PPPres = Nothing
Set pp = Nothing
End Sub
答案 0 :(得分:0)
您不需要将Range
转换为字符串,您需要使用其地址属性,该属性已经是字符串
Sub SelectRange()
Dim Rng1 As Range
Set Rng1 = Application.InputBox("select cell", Type:=8)
MsgBox ("You selected " & Rng1.Address & "as the range")
End Sub
答案 1 :(得分:0)
您需要使用Range.Address属性,如下所示:
Sub SelectRange()
Dim Rng1 As Range
On Error Resume Next 'If the user presses cancel, it would cause an error
Set Rng1 = Application.InputBox("Select Cell", "Range Selection", Selection.Address, Type:=8)
On Error GoTo 0 'Remove the On Error Resume Next condition
If Rng1 Is Nothing Then Exit Sub 'Pressed cancel
MsgBox ("You selected " & Rng1.Address & " as the range")
End Sub
我还想确保用户按下取消时不会出现错误,我希望将当前选择用作默认值。