为用户选择的范围创建循环

时间:2020-06-27 13:52:13

标签: excel vba

开发一个代码,用户可以通过该代码在活动工作簿中选择一个范围。对于选定的范围,即A8:A12,我要运行一个循环,对于选定范围内的每个范围,循环将使用其值,使用该值过滤GL_Sheet的当前区域(GL_Rng)并复制可见单元格 代码是

'Declaring Workbooks
Dim GL_CY As Variant
Dim GL_Book As Workbook, Tgt_Book As Workbook
GL_CY = Application.GetOpenFilename(Title:="Open GL", FileFilter:="Excel Files (*.xls*),*xls*")
Set GL_Book = Application.Workbooks.Open(GL_CY)
Set Tgt_Book = Workbooks.Add


'Selecting Range
Dim GL_Code As Variant, GL_LR As Long, GL_Rng As range, Rng As range
Dim GL_Sheet As Worksheet, tgt As Worksheet
Set GL_Sheet = GL_Book.Worksheets(1)
GL_LR = GL_Sheet.range("B" & Rows.Count).End(xlUp).Row
Set GL_Rng = GL_Sheet.range("A4:R" & GL_LR).CurrentRegion.Offset(3, 0)
GL_Code = Application.InputBox(Prompt:="Select the range of GL codes to generate its GL activity ", Title:="Generate GL Activity", Type:=8)
' GL_Sheet.range("A3:A5").Value = range(GL_Code).Value



For Each Rng In range(GL_Code)
    Set tgt = Tgt_Book.Worksheets.Add
    GL_Rng.AutoFilter Field:=6, Criteria1:=GL_Code
    GL_Rng.SpecialCells(xlCellTypeVisible).Copy
    tgt.Paste
    tgt.range("A1").CurrentRegion.Cut tgt.range("B6")
    tgt.Cells.WrapText = False
    tgt.Cells.Columns.AutoFit
    tgt.Name = GL_Code
    Application.CutCopyMode = False
   Next Rng

如您所见,我在代码的最后部分苦苦挣扎,这会导致错误1004(范围方法...)

1 个答案:

答案 0 :(得分:0)

Naqi,

我创建了一个小测试例程,以检查从InputBox返回的内容。 轮到它以变体形式回来了。我尝试将其设置为范围,但这也不起作用。但是,更改Type:= 2(字符串)可以使其工作

Option Explicit

Sub Test()

Dim GL_Code As String

GL_Code = Application.InputBox(Prompt:="Select the range of GL codes to generate its GL activity ", _
                               Title:="Generate GL Activity", _
                               Type:=2)
                               
Debug.Print Range(GL_Code).Address()

End Sub

'So by changing your Type to 2 the For Each rng statement should no longer create a problem.

Edit: Found an option using Type 8:
[Click here for the post I found this in.][1]

Sub MyMacro()

Dim GL_Code As Range
Set GL_Code = Application.InputBox("Select a range", "Get Range", Type:=8)

Debug.Print GL_Code.Address()

End Sub

'Since GL_Code is now a range your For Each should NOT enclose it in a Range() function!

HTH