2017-06-04 252 views
1

我有一个愚蠢的问题,不知道为什么..VBA:问题Application.CountIf

我想从另一个工作簿中导入一些值。

步骤:

- 开放的其他工作簿(源)

- 获得所需的数据范围。

- 复制数据

- 获取节点的出现次数*使目标表准备。

- 切换到目标表并获取节点外观。

- 展开目标表。

- 粘贴数据。

我的问题: 它只能从SORCE表得到COUNTIF价值..

以下一些信息:

Sub import_kundenform() 

Dim LR As Long 
Dim rng As Range 
Dim rng2 As Range 
Dim ActRow As Integer 

actwb = ActiveWorkbook.Name 
actsh = ActiveSheet.Name 

fName = Application _ 
.GetOpenFilename("Excel Files (*.xls), *.xls") 

If fName = False Then 
    Exit Sub 
End If 

Set wb = Workbooks.Open(fName) 
startCell = 19 
wb.Activate 
LR = Cells(Rows.Count, "A").End(xlUp).Row 

Set rng = Range("B1:B" & LR) 
wb.Sheets(1).Range("A7:L" & LR).Copy 
ival = Application.CountIf(rng, "node*") 
Workbooks(actwb).Worksheets(actsh).Activate 

ival2 = Application.CountIf(rng, "node*") 
If ival > ival2 Then 
    ActRow = ival - ival2 + startCell 
    Range("A20:A" & ActRow).EntireRow.Insert 
ElseIf ival < ival2 Then 
    ActRow = ival2 - ival + startCell 
    Range("A20:A" & ActRow).EntireRow.Insert 
End If 
Workbooks(actwb).Sheets(actsh).Range("A1").PasteSpecial Paste:=xlPasteValues 

End Sub 

如果有你需要知道的请让我知道的任何信息。

我希望你能帮助我。

回答

0
wb.Activate 
LR = Cells(Rows.Count, "A").End(xlUp).Row 

Set rng = Range("B1:B" & LR) 
wb.Sheets(1).Range("A7:L" & LR).Copy 
ival = Application.CountIf(rng, "node*") 

Workbooks(actwb).Worksheets(actsh).Activate 
ival2 = Application.CountIf(rng, "node*") 
If ival > ival2 Then 

两个ivalival2从相同的范围rng计算。激活另一个工作簿或工作表不会更改范围变量rng

您想从另一个WB同一范围内得到ival2/WS激活后,尝试

ival2 = Application.CountIf(Range(rng.Address), "node*") 
'       ^^^^^^^^^^^^^^^^^^ 

现在将指向同一个范围,但在活动工作表。

但是,强烈建议使用完全的Activate东西,工作始终符合完全合格的范围下降。

Set wb = Workbooks.Open(fName) 
    startCell = 19 
    'wb.Activate ' <----------drop this 
    With wb.Sheets(1) 
    LR = .Cells(.Rows.count, "A").End(xlUp).row 
    Set rng = .Range("B1:B" & LR) 
    .Range("A7:L" & LR).Copy 
    ival = Application.CountIf(rng, "node*") 
    End With 

    'Workbooks(actwb).Worksheets(actsh).Activate  ' <----------drop this 
    With Workbooks(actwb).Worksheets(actsh) 
    ival2 = Application.CountIf(.Range(rng.Address), "node*") 
    If ival > ival2 Then 
     ActRow = ival - ival2 + startCell 
     .Range("A20:A" & ActRow).EntireRow.Insert 
    ElseIf ival < ival2 Then 
     ActRow = ival2 - ival + startCell 
     .Range("A20:A" & ActRow).EntireRow.Insert 
    End If 
    .Range("A1").PasteSpecial Paste:=xlPasteValues 
    End With 
+1

非常感谢!我将在未来做:)感谢您的帮助! – Kalain

+0

@Kalain欢迎您。很高兴知道它帮助:) –