How to transfer multiple Data in one excel Workbook to another excel workbook - excel

I am hoping you could help me, make a Code for an Update button. I wanted to have a 1 workbook -Enter Data, that when I feel up the workbook, and click the update button, it will automatically update specific workbook, base on the workbook file. mentioned in the EnterData Workbook.
Eg. I want to Make EnterData with following Details.
ItemName:
Item Quantity:
Department: 3 Department per month
Sheet Name: Month
FileName: Depends on the ItemName
and once I click the update button, it will automatically update the specific file with the specific sheet name and department
Hope you could help me with this.

This will get you a good head start
I try to divide the work to be performed into simple, readable, and logical task.
Use Constants for settings such as: Root Directories, Cell References, Column References
I want to see this in the top of a module
Public Const TartgetWorkBookName As String = "C:\Users\SomeFolder\Data.xlsm"
Public Const TartgetWorkSheetName As String = "Sheet3"
Public Const TartgetTopLeftCellAddress As String = "A1"
Versus this somewhere buried in code:
Dim TargetWorkBook As Workbook
Set TargetWorkBook = Application.Workbooks.Open("C:\Users\SomeFolder\Data.xlsm")
Set getTargetR1C1 = TargetWorkBook.Worksheets("Sheet3").Range("A1")
Here is a rough draft of a basic pattern that I follow. It is a working example.
Option Explicit
Const TartgetWorkBookName As String = "C:\Users\SomeFolder\Data.xlsm"
Const TartgetWorkSheetName As String = "Sheet3"
Const TartgetTopLeftCellAddress As String = "A1"
Dim TargetWorkBook As Workbook
Set TargetWorkBook = Application.Workbooks.Open(TartgetWorkBookName)
Set getTargetR1C1 = TargetWorkBook.Worksheets(TartgetWorkSheetName).Range(TartgetTopLeftCellAddress)
Sub PostRecord()
Dim TargetR1C1 As Range, ItemName As String, Qty As Double, Department As String, Month_ As Integer
Set TargetR1C1 = getTargetR1C1()
'If your transfering a lot of data turn off
Speedboost True
'------Begin Loop
'------For x = 2 to LastColumn
'------Set Variables
ItemName = "Dragon Sauce"
Qty = 3
Department = "Spicy Hot Stuff"
Month_ = Month(Date)
'------Post Varibles to taget
UpdateRecord TargetR1C1, ItemName, Qty, Department, Month_
'Next
'Turn Everything back on
Speedboost False
End Sub
Sub UpdateRecord(TargetR1C1 As Range, ItemName As String, Qty As Double, Department As String, Month_ As Integer)
Dim c As Range
Dim x As Long, y As Long
If Len(TargetR1C1.Offset(1)) Then
x = TargetR1C1.End(xlDown).Row + 1
Else
x = TargetR1C1.Rows + 1
End If
y = TargetR1C1.Column
Set c = TargetR1C1.Cells
c(x, y) = ItemName
c(x, y + 1) = Qty
c(x, y + 2) = Department
c(x, y + 3) = Month_
End Sub
Sub Speedboost(bSpeedUpMacros As Boolean)
With Application
.ScreenUpdating = Not (bSpeedUpMacros)
.EnableEvents = Not (bSpeedUpMacros)
If bSpeedUpMacros Then
.Calculation = xlCalculationManual
Else
.Calculation = xlCalculationAutomatic
End If
End With
End Sub
Function getTargetR1C1() As Range
Dim TargetWorkBook As Workbook
Set TargetWorkBook = Application.Workbooks.Open(TartgetWorkBookName)
Set getTargetR1C1 = TargetWorkBook.Worksheets(TartgetWorkSheetName).Range(TartgetTopLeftCellAddress)
End Function

Related

validate strings in an excel in vb.net

I have a question, in vb.net, how can i validate that 2 values are the same in an excel in vb.net
for example i have defined 3 list
Public NSPS As New List(Of String)
Public CONTAINER As New List(Of String)
Public CONTAINER2 As New List(Of String)
I have 2 excel files where CONTAINER and CONTAINER2 are id's
So i need to create a third excel file that filters only the id's that repeat themselves in the 2 excel
meaning if i have an id: CARU9891569 in the 2 files, only then it transfers to the generated excel
and the 2 excel's have some extra information, for example: excel 1 has the variables: DELIVERY, CONTAINER, VOLUME.
the second excel has the variables: NSPS, NPOS, PACKAGES, CONTAINER2
SO the generated excel needs to have all of the variables: DELIVERY, CONTAINER, VOLUME, NSPS, NPOS, PACKAGES. using CONTAINER as the filter
to just fill information in a new excel i use this code
i use a function like this to extract the information from the excel files
Function extraer_valores_planilla(ByRef ruta As String) As Boolean
ExcelPackage.LicenseContext = LicenseContext.NonCommercial
Try
Dim stream = System.IO.File.OpenRead(ruta)
Dim package = New OfficeOpenXml.ExcelPackage(stream)
'// Libro
Dim Workbook = package.Workbook
'// Hojas
Dim hojas = Workbook.Worksheets
' While (Workbook.Worksheets.Count >= aux)
Dim hojaUsuarios = Workbook.Worksheets(Workbook.Worksheets.Item(0).ToString)
Dim indice As Integer = 2
While (indice < 5000)
'Numero entrega'
If (IsNothing(hojaUsuarios.Cells("A" & indice).Value) = False) Then
NSPS.Add(hojaUsuarios.Cells("A" & indice).Value)
End If
indice += 1
End While
indice += 1
Catch EX As Exception
MsgBox(EX.ToString)
Return False
End Try
Return True
and then i fill the third excel like this
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
ExcelPackage.LicenseContext = LicenseContext.NonCommercial
Dim path As String = seleccionardirectorio("Excel|.xlsx")
If (String.IsNullOrWhiteSpace(path) = False) Then
Dim excel = New ExcelPackage(New FileInfo(path))
excel.Workbook.Worksheets.Add("Hoja1")
Dim aux As Integer = 1
Dim Workbook = excel.Workbook
Dim hojas = Workbook.Worksheets
Dim dict As New Dictionary(Of String, String)
Dim hoja1 = Workbook.Worksheets("Hoja1")
'DAMOS NOMBRE A LAS COLUMNAS
INICIALIZAR_PLANILLA(hoja1)
While (aux <= CONTAINER.Count)
hoja1.Cells("C" & aux + 1).Value = ENTREGA.Item(aux - 1)
aux += 1
End While
this is the same for all variables i just resume for you guys and this works just fine.
should i use 2 cicles to filter the excel, maybe a for each, sorry i am new to programing and i am stuck in this part
any ideas would be helpfull
Thanks in advance!
yes, use 2 for each loops.
for each item in list
for each otheritem in list2
if item = otheritem then
' These items match
end if
next
next
Replace the dummy variables with yours

A value used in the formula is of the wrong data type" error - vba

I have a function that prints the time to an excel in 5 lots each. I have a function that first stores time in collection object and then converts it to an array & finally this function would call another function to populate the array in to excel.
Below my function for your reference.
Public daytime_store As New Collection
Public daytime_tm As New Collection
Public daytime_store_cnt As New Collection
Option Explicit
Function n50_store_day()
Dim I_day As Date, Currtime_cutoff As Date, daytime_store_arr As Variant, daytime_tm_arr As Variant, lx As Integer, ly As Integer
I_day = Format(Now(), "hh:mm:ss")
daytime_store.Add I_day
If daytime_store.Count = 5 Then
daytime_store_cnt.Add 5
ly = daytime_store_cnt.Count
If ly = 1 Then lx = 1
If ly > 1 Then lx = ((ly - 1) * 5) + 1
daytime_store_arr = CollectionToArray(daytime_store)
Set daytime_store = New Collection
Call varitoxl(daytime_store_arr, lx)
End If
End Function
This is working perfectly if i run the function from F5 but showing wrong data type error if called from a spread sheet. Would anyone guide on this.
Also below function of varitoxl:
Function varitoxl(dlr As Variant, yz As Integer) As Variant
Dim strFilename As String: strFilename = "C:\Users\Acer\Desktop\n50imp\book1.xlsx"
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:=strFilename)
Dim ws As Worksheet
Set ws = wb.Worksheets("sheet1")
Debug.Print 1
ws.Cells(yz, 1).Resize(5, 1) = dlr
Debug.Print 2
ActiveWorkbook.Close SaveChanges:=True
End Function

Copying data from one spreadsheet to another using Macro and ActiveControl Button

I'm trying to write a macro which will copy data from one spreadsheet to another spreadsheet within the same workbook using Marco assigned to a active control button. Also, I would the button to clear the data from fields after copying to the other sheet. However, I'm struggling to Debug this code. Can anyone offer assistance?
Private Sub CommandButton1_Click()
Dim OrderDate As String, Job As String, AccountManager As String
Dim Site As String, DueDate As String, BudgetedHours As String
`enter code here`Supervisor As String
Dim TotalPieces As String, Billedhours As String, UnitsCompleted As String
Dim EmployeeName As String, Task As String
Dim StartTime As String, FinishTime As String, TotalTime As String
Dim Notes As String
Worksheets("Assembly Work Form").Select
Date = Range("B3")
Job = Range("B4")
CustomerName = Range("B5")
AccountManager = Range("B7")
Supervisor = Range("B8")
Site = Range("B9")
DueDate = Range("B10")
BudgetedHours = Range("B11")
TotalPieces = Range("F5")
Billedhours = Range("F3")
UnitsCompleted = Range("F6")
EmployeeName = Range("B15")
Task = Range("B15")
StartTime = ("E17")
FinishTime = ("G17")
TotalTime = ("I17")
Notes = Range("K17")
Worksheets("AssemblyTotals").Select
Worksheets("AssemblyTotals").Range("A2").Select
If Worksheets("AssemblyTotals").Range("A3").Offset("1,0") <> "" Then
Worksheets("AssemblyTotals").Range("A2").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = Date
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Job
ActiveCell.Offset(-1, 0).Select`enter code here`
ActiveCell.Value = CustomerName
Worksheets("Assembly Work Form").Select
Worksheets("Assembly Work Form").Range("DataFields").ClearContents
End Sub
Basically, what you want to do is the following:
Private Sub CommandButton1_Click()
Worksheets("AssemblyTotals").Range("SomeTargetAddress").Value = Worksheets("Assembly Work Form").Range("SomeSourceAddress").Value 'Copy a value
Worksheets("Assembly Work Form").Range("SomeSourceAddress").ClearContents 'Clear the original value
End Sub
Of course change the "SomeTargetAddress" and "SomeSourceAddress" to valid cell references. Also keep in mind you can do multiple cells at once:
Private Sub CommandButton1_Click()
Worksheets("AssemblyTotals").Range("A2:A100").Value = Worksheets("Assembly Work Form").Range("A2:A100").Value 'Do 99 cells at once
End Sub
And if you want to start on the first empty row:
Private Sub CommandButton1_Click()
Dim wr as Long 'Variable to store the row
wr = Worksheets("AssemblyTotals").Range("A2").End(xlDown).Row + 1
Worksheets("AssemblyTotals").Range("A" & wr).Value = Worksheets("Assembly Work Form").Range("A2:A100").Value 'Do 99 cells at once starting at the first empty row in Column A.
End Sub
No need to store everything in variables first, unless you intend to use those variables in more places later on. Also, note that you shouldn't use ActiveCell and Select, etc. as mentioned in my comment.
Based on the above, all you have to do now is just map the cells correctly and that's it.

Excel VBA - how to find the largest substring value in a column

I have a column in a spreadsheet.
The format of the data in each cell is aa-0001-xx.
I need to examine the whole column to find the highest value of the sequence number. this would be the substring from column4 thru column7.
I can find the sequence number using Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4)
But I need to find the max sequence in the whole column.
I am doing this in VBA.
Any help would be appreciated.
Here is my code so far:
Private Sub CommandButton1_Click()
Dim sQuoteNumber As String
Dim sFileName As String
Dim sPathName As String
Dim checkit As String
'Log the Quote
'First, open the log file and determine the next sequential log number.
sPathName = "C:\Users\Rich\Documents\Bryan\BigProject\"
sFileName = "QuoteLog2016.xlsx"
ControlFile = ActiveWorkbook.Name
Workbooks.Open Filename:=sPathName & sFileName
'Create the new Quote Number
checkit = Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4) ' This is a temp test line
If Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4) = "" Then
sQuoteNumber = "16-0001"
Else
'find the biggest number
'Here I was looking to like pass the mid function to a Max function of some sort.
sQuoteNumber = "16-0002"
End If
MsgBox ("The new Quote Number is: " + sQuoteNumber)
'Save the log entry
Workbooks(sFileName).Close
All of the comments made to your answer would work well for you. It's also true that there's no evidence in your code at having attempted something, however rudimentary, and this is why answers to a rather trivial task are not forthcoming for you. Perhaps, in future, have a go at some kind of solution ( even if it feels more guesswork than anything) and people on this site will be much more supportive of you.
To set you on your way, you could make use of the Split() function which converts a String into a String array, separated by a nominated value - in the case of your quotations, you could use "-" as your separator. This might be easier than your Mid function and will deal with the case of different sized quotations.
The code below will get you started but you'd want some error handling in there to test, for example, that each cell splits appropriately or that any cells aren't blank. I'll leave all of that to you.
Option Explicit
Private mLastQuote As Long
Public Sub Test()
Initialise 'call this routine just once at the start of your project
MsgBox GetNextQuote(16) 'use the GetNextQuote() function to get next number
MsgBox GetNextQuote(16)
MsgBox GetNextQuote(16)
End Sub
Private Function GetNextQuote(prefix As Integer) As String
mLastQuote = mLastQuote + 1
GetNextQuote = CStr(prefix) & "-" & _
Format(mLastQuote, "000#")
End Function
Private Sub Initialise()
Const PATH_NAME As String = "C:\Users\Rich\Documents\Bryan\BigProject\"
Const FILE_NAME As String = "QuoteLog2016.xlsx"
Const QUOTE_COL As String = "B"
Dim wb As Workbook
Dim ws As Worksheet
Dim v As Variant
Dim r As Long
Dim parts() As String
Dim num As Long
Application.ScreenUpdating = False
Set wb = Workbooks.Open(PATH_NAME & FILE_NAME, True, True)
Set ws = wb.Worksheets("Sheet1")
'Read quote values into variant array
With ws
v = .Range(.Cells(2, QUOTE_COL), _
.Cells(.Rows.Count, QUOTE_COL).End(xlUp)) _
.Value2
End With
'Find max quote
For r = 1 To UBound(v, 1)
parts = Split(v(r, 1), "-") 'splits quote into 3 parts
num = CLng(parts(1)) 'index (1) is the middle part
If num > mLastQuote Then mLastQuote = num
Next
wb.Close False
Application.ScreenUpdating = True
End Sub

VBA code running horrendously slow

I have a loop that can go on for ages, although the "Enheder" worksheet only has like 10 rows, and the dataset im loadin has maybe 300 rows, it's taking a REALLY long time when I try to import.
Public Function ImportData()
Dim resultWorkbook As Workbook
Dim curWorkbook As Workbook
Dim importsheet As Worksheet
Dim debugsheet As Worksheet
Dim spgsheet As Worksheet
Dim totalposts As Integer
Dim year As String
Dim month As String
Dim week As String
Dim Hospital As String
Dim varType As String
Dim numrows As Integer
Dim Rng As Range
Dim colavg As String
Dim timer As String
Dim varKey As String
year = ImportWindow.ddYear.value
month = ImportWindow.ddMonth.value
week = "1"
varType = ImportWindow.ddType.value
Hospital = ImportWindow.txtHospital.value
Set debugsheet = ActiveWorkbook.Sheets("Data")
Set spgsheet = ActiveWorkbook.Sheets("Spørgsmål")
Set depsheet = ActiveWorkbook.Sheets("Enheder")
Set resultWorkbook = OpenWorkbook()
setResultColVars debugsheet
'set sheets
Set importsheet = resultWorkbook.Sheets("Dataset")
numrows = debugsheet.UsedRange.Rows.Count
'make sure that the enhed can be found in the importsheet, so the units can be extracted accordingly
If Not (importsheet.UsedRange.Find("afdeling") Is Nothing) Then
Dim DepColumn
Dim aCell
DepColumn = importsheet.UsedRange.Find("afdeling").column
'sort importsheet to allow meaningfull row calculations
Set aCell = importsheet.UsedRange.Columns(DepColumn)
importsheet.UsedRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes
Dim tempRange As Range
Dim SecColumn
Dim secRange As Range
'find row ranges for departments
Application.ScreenUpdating = False
'**Here's the loop that will go on for aaaaaages until I decide to ctrl+pause**
For Each c In depsheet.UsedRange.Columns(1).Cells
splStr = Split(c.value, "_")
If UBound(splStr) = -1 Then
ElseIf UBound(splStr) = 0 Then
totalposts = totalposts + IterateColumns(GetRowRange(importsheet, DepColumn, splStr(0)), spgsheet, importsheet, debugsheet, year, month, week, Hospital, splStr(0), 0, varType, False)
ElseIf UBound(splStr) = 1 And Not (importsheet.UsedRange.Find("afdeling_" & splStr(0)) Is Nothing) Then
totalposts = totalposts + IterateColumns(GetRowRange(importsheet, importsheet.UsedRange.Find("afdeling_" & splStr(0)).column, splStr(1)), spgsheet, importsheet, debugsheet, year, month, week, Hospital, splStr(0), splStr(1), varType, False)
End If
Next
Application.ScreenUpdating = True
' go through columns to get total scores
totalposts = totalposts + IterateColumns(importsheet.UsedRange, spgsheet, importsheet, debugsheet, year, month, week, Hospital, 0, 0, varType, True)
resultWorkbook.Close Saved = True
ResultsWindow.lblPoster.Caption = totalposts
ImportWindow.Hide
ResultsWindow.Show
Else
MsgBox "Kunne ikke finde afdelingskolonnen. Kontroller at der er er en kolonne med navnet 'afdeling' i dit datasæt"
End If
End Function
Function GetRowRange(sheetRange, column, value) As Range
'check for a valid section column
sheetRange.AutoFilterMode = False
sheetRange.UsedRange.AutoFilter Field:=column, Criteria1:=value
Set GetRowRange = sheetRange.UsedRange.SpecialCells(xlCellTypeVisible)
sheetRange.AutoFilterMode = False
End Function
'iterates through columns of a range to get the averages based on the column headers
Function IterateColumns(varRange As Range, spgsheet, importsheet, resultsheet, year, month, week, Hospital, dep, sec, varType, sortspg As Boolean)
Dim numrows
Dim totalposts
Dim usedRng
totalposts = 0
numrows = resultsheet.UsedRange.Rows.Count
Dim insert
insert = True
If Not (varRange Is Nothing) Then
' go through columns to get scores
For i = 1 To varRange.Columns.Count
Dim tempi
tempi = numrows + totalposts + 1
Set Rng = varRange.Columns(i)
With Application.WorksheetFunction
'make sure that the values can calculate
If (.CountIf(Rng, "<3") > 0) Then
colavg = .SumIf(Rng, "<3") / .CountIf(Rng, "<3")
insert = True
Else
insert = False
End If
End With
'key is the variable
varKey = importsheet.Cells(1, i)
'only add datarow if the data matches a spg, and the datarow is not actually a department
If (sortSpgs(varKey, spgsheet, sortspg)) And (insert) And Not (InStr(key, "afdeling")) Then
resultsheet.Cells(tempi, WyearCol).value = year
resultsheet.Cells(tempi, WmonthCol).value = month
resultsheet.Cells(tempi, WweekCol).value = "1"
resultsheet.Cells(tempi, WhospCol).value = "Newport Hospital"
resultsheet.Cells(tempi, WdepCol).value = "=VLOOKUP(N" & tempi & ",Enheder!$A:$B,2,0)"
resultsheet.Cells(tempi, WsecCol).value = "=IFERROR(VLOOKUP(O" & tempi & ",Enheder!$A:$B,2,0),"" "")"
resultsheet.Cells(tempi, WdepnrCol).value = dep
resultsheet.Cells(tempi, WsecnrCol).value = dep & "_" & sec
resultsheet.Cells(tempi, WjtypeCol).value = varType
resultsheet.Cells(tempi, WspgCol).value = varKey
resultsheet.Cells(tempi, WsporgCol).value = "=VLOOKUP(H" & tempi & ",Spørgsmål!$D:$I,6,0)"
resultsheet.Cells(tempi, WtestCol).value = ""
resultsheet.Cells(tempi, Wsv1Col).value = colavg
resultsheet.Cells(tempi, Wsv2Col).value = (1 - colavg)
resultsheet.Cells(tempi, Wsv3Col).value = ""
resultsheet.Cells(tempi, WgrpCol).value = "=VLOOKUP(H" & tempi & ",Spørgsmål!$D:$I,4,0)"
totalposts = totalposts + 1
End If
Next
End If
IterateColumns = totalposts
End Function
'Function that gets the workbook for import
Function OpenWorkbook()
Dim pathString As String
Dim resultWorkbook As Workbook
pathString = Application.GetOpenFilename(fileFilter:="All Files (*.*), *.*")
' check if it's already opened
For Each wb In Workbooks
If InStr(pathString, wb.Name) > 0 Then
Set resultWorkbook = wb
Exit For
End If
Next wb
If Not found Then
Set resultWorkbook = Workbooks.Open(pathString)
End If
Set OpenWorkbook = resultWorkbook
End Function
'find column numbers for resultsheet instead of having to do this in every insert
Function setResultColVars(rsheet)
WyearCol = rsheet.UsedRange.Find("År").column
WmonthCol = rsheet.UsedRange.Find("Måned").column
WweekCol = rsheet.UsedRange.Find("Uge").column
WhospCol = rsheet.UsedRange.Find("Hospital").column
WdepCol = rsheet.UsedRange.Find("Afdeling").column
WsecCol = rsheet.UsedRange.Find("Afsnit").column
WdepnrCol = rsheet.UsedRange.Find("Afdelingsnr").column
WsecnrCol = rsheet.UsedRange.Find("Afsnitnr").column
WjtypeCol = rsheet.UsedRange.Find("Journaltype").column
WspgCol = rsheet.UsedRange.Find("spg").column
WsporgCol = rsheet.UsedRange.Find("spørgsmål").column
WtestCol = rsheet.UsedRange.Find("test").column
Wsv1Col = rsheet.UsedRange.Find("Svar 1").column
Wsv2Col = rsheet.UsedRange.Find("Svar 0").column
Wsv3Col = rsheet.UsedRange.Find("Svar 3").column
WgrpCol = rsheet.UsedRange.Find("Gruppering").column
End Function
Function sortSpgs(key, sheet, sortspg As Boolean)
If Not (sheet.UsedRange.Find(key) Is Nothing) Then
If (sortspg) Then
ResultsWindow.lstGenkendt.AddItem key
End If
sortSpgs = True
Else
If (sortspg) Then
ResultsWindow.lstUgenkendt.AddItem key
End If
sortSpgs = False
End If
End Function
Function Progress()
iProgress = iProgress + 1
Application.StatusBar = iProgress & "% Completed"
End Function
Difficult to debug without the source files.
I see the following potential problems:
GetRowRange: .UsedRange might return more columns than you expect. Check by pressing Ctrl-End in the worksheet and see where you end up
Some thing in your main routine - depsheet.UsedRange.Columns(1).Cells might just result in much more rows than expected
someRange.Value = "VLOOKUP(... will store the formula as text. You need .Formula = instead of .Value (this will not solve your long runtime but certainly avoid another bug)
In sortSpgs you add know or unknow items to a control. Not knowing if there's any event code behind these controls, disable events with Application.EnableEvents=False (ideally in the beginning of your main sub together with the .ScreenUpdating = False)
Also, set Application.Calculation = xlCalculationManual at the beginning and Application.Calculation = xlCalculationAutomatic at the end of your code
You're performing a lot of .Find - esp. in sortSpgs - this is potentially slow in large sheets, as it has to loop over quite some data, depending on the underlying range.
Generally, a few more "best practise remarks":
* Dim your variables with the correct types, same for returns of functions
* Use With obj to make the code cleaner. E.g. in setResulcolVars you could use With rsheet.UsedRange and remove this part in the following 15 or so lines
* In modules of small scope, it is okay to dim some variable with a module wide scope - esp. if you hand them over with every call. This will make your code much easier to read
Hope that helps a bit... mvh /P.
My guess is that Application.Screenupdating is the problem. You set to false inside the:
if Not (importsheet.UsedRange.Find("afdeling") Is Nothing) Then
block. So if the isn't the case then screenupdateing isn't disabled. you should move it to the beginning of the function.
you could also try to write the usedrange in an array, work with it , and write it back if needed.
code example
dim MyArr() as Variant
redim MyArray (1 to usedrange.rows.count, 1 to usedrange.columns)
MyArray=usedrange.value
'calculating with Myarray instead of ranges (faster)
usedrange.value=myarray 'writes changes back to the sheet/range
also, maybe you can use .match instead of .find, wich is faster.
with arrays you use application.match( SearchValue, Array_Name, False) 'false if for exact match
the same thing works for range.find() , becoming application.find()...
save first your master workbook under a new name before making such a big change...

Resources