2017-06-04 36 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歡迎您。很高興知道它幫助:) –