Using VB.Net Read from file, edt cells and finally save - vb.net

Public Function SetInfo(ByRef place As String, ByRef name As String) As Boolean
Dim Completed As Boolean = False
Dim MyExcel As New Excel.Application
Dim myworkbook As New Excel.Workbook
myworkbook = MyExcel.Workbooks.Open(place)
MyExcel.Workbooks.Open(place)
Dim x As Integer
Dim y As Integer
Dim finish As Boolean = False
MyExcel.Sheets("Sheet1").activate()
MyExcel.Range("B1").Activate()
Do
If MyExcel.ActiveCell.Value = name Then
Exit Do
Else
MyExcel.ActiveCell.Offset(0, 1).Activate()
End If
Loop
Do
If MyExcel.ActiveCell.Text = "" Then
MyExcel.ActiveCell.Value = "attended"
MsgBox("Wrote.")
Exit Do
Else
MyExcel.ActiveCell.Offset(1, 0).Activate()
End If
Loop
myworkbook.Save()
MyExcel.Workbooks.Close()
MyExcel = Nothing
Return finish
End Function
I will explain this code.
Start with Cell B1, and whenever the cell doesn't include what I wanted, the activate cell go right.
And if the cell is what I wanted, it goes down until program find blank space.
And in this process, there's no problem.
In saving process, it occurs problem.
If I delete these section
Dim myworkbook As New Excel.Workbook
myworkbook = MyExcel.Workbooks.Open(place)
and
myworkbook.Save()
"Something has been change, will you save it?" this Excel messagebox comes out.
And I don't want to see the messagebox and I want to save it in my program.
What should I do?
PS.Sry for my bad English.

Application.DisplayAlerts = False
myworkbook.Save()
Application.DisplayAlerts = True
Or you can use .saveAs()
msdn: http://msdn.microsoft.com/de-de/library/microsoft.office.tools.excel.workbook.saveas(v=vs.80).aspx
see: Saveas issue Overwrite existing file ( Excel VBA)
Sub Sample()
Dim fName As Object
'~~> Offer user to Save the file at a particular location
fName = Application.GetSaveAsFilename
'~~> Check if it is a valid entry
If fName <> False Then
'~~> Check before hand if the file exists
If Not Dir(fName) <> "" Then
'~~> If not then save it
ActiveWorkbook.SaveAs Filename:=fName
Else
'~~> Trap the error and ignore it
On Error Resume Next
If Err.Number = 1004 Then
On Error GoTo 0
Else '<~~ If user presses Save
ActiveWorkbook.SaveAs(Filename:=fName, _
FileFormat:=xlWorkbook, _
ConflictResolution:=xlLocalSessionChanges)
End If
End If
End If
End Sub

Related

How to use VBA to duplicate a sheet and then rename it (all in one sub)?

I am able to rename the activesheet using the following code but need to combine this with (first) duplicating the original sheet:
Sub CopySheet()
Dim strName As String
strName = InputBox("Budget2")
If strName = "" Then
Beep
Exit Sub
End If
ActiveSheet.Copy
ActiveSheet.Name = strName
End Sub
Per the documentation for the Worksheet.Copy method, using it without specifying either the Before or After argument will create a new Workbook, containing only that Worksheet.
So, to add a copy of the ActiveSheet after the ActiveSheet in the same Workbook, you can just change ActiveSheet.Copy to ActiveSheet.Copy After:=ActiveSheet
Make sure you check if the new sheet name already exists.
Make sure you keep track of where the copied sheet appears eg. after the source sheet SourceSheet.Copy After:=SourceSheet so you can pick up it's index which is 1 after the source sheet's: Set NewSheet = ThisWorkbook.Sheets(SourceSheet.Index + 1).
Finally make sure to catch errors on renaming if user entered not allowed characters or too long sheet names.
So you would end up with something like:
Option Explicit
Public Sub CopySheet()
Dim InputName As String
InputName = Application.InputBox("Budget2", Type:=2) '2 = text: https://learn.microsoft.com/en-us/office/vba/api/excel.application.inputbox#remarks
' user pressed cancel or entered nothing
If (VarType(InputName) = vbBoolean And InputName = False) Or InputName = vbNullString Then
Beep
Exit Sub
End If
' check if new sheet name already exists
On Error Resume Next
Dim TmpWs As Object
Set TmpWs = ThisWorkbook.Sheets(InputName)
On Error GoTo 0
If Not TmpWs Is Nothing Then
MsgBox "The Sheet '" & InputName & "' already exists", vbCritical
Exit Sub
End If
Dim SourceSheet As Object
Set SourceSheet = ActiveSheet
SourceSheet.Copy After:=SourceSheet
Dim NewSheet As Object
Set NewSheet = ThisWorkbook.Sheets(SourceSheet.Index + 1)
On Error GoTo ERR_RENAME
NewSheet.Name = "InputName"
On Error GoTo 0
Exit Sub
ERR_RENAME:
MsgBox "Sheet could not be renamed.", vbCritical
Err.Clear
End Sub

Excel VBA - On Error Execute Code

Im using Application.FileDialog(msoFileDialogFolderPicker) to choose a folder. This is executed by using a button in userform. However before the user choose the folder a new sheet will be created. Then the open file dialog [Application.FileDialog(msoFileDialogFolderPicker)] will pop up.
Function SelectFolder(Optional msg As String) As String
Dim diaFolder As FileDialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Title = msg
diaFolder.Show
On Error Resume Next
SelectFolder = diaFolder.SelectedItems(1)
On Error GoTo 0
Set diaFolder = Nothing
End Function
The problem arises when user decided to cancel to choose the folder. When this happen, the newly created sheet should be deleted. I tried to use error handler but now luck.
ErrorHandler:
If SheetExists("MS") Then Application.Run "DeleteSheet.deleteSh1"
If SheetExists("MS2") Then Application.Run "DeleteSheet.deleteSh2"
If SheetExists("MT") Then Application.Run "DeleteSheet.deleteSh3"
Application.Run "HideSheets.hideSh"
Resume Next
Exit Sub
Hope you guys can give some idea on this.
why not create the sheet when you have a valid response?
That said, you could check the length of the string you are looking for - 0 means cancel, i.e.
Dim strResponse As String
strResponse = SelectFolder("test")
If Len(strResponse) = 0 Then
MsgBox "user cancelled", vbCritical
'delete sheet
End If
I imagine the above routine SelectFolder is called somehow from a sub that first creates a worksheet then calls it. You could achieve your goal like this:
Sub MyButton_Click()
Dim newWS as worksheet, folder as String
set newWS = sheets.Add
folder = SelectFolder("please select your folder")
If folder = "" Then
newWS.Delete
Else
' ... proceed with the selected folder
End If
End Sub
However, creating the Worksheet before getting the user's answer doesn't seem to me like a good approach, unless there's some strong reason.

Get Worksheet Names of Opened Workbook

I have the below code where the user is promted to select a workbook, I want to ensure that the user is selecting a specific file, and to do this I want to verify upon opening the workbook that the Sheet names are matching what I am expecting them to be:
Private Sub CommandButton1_Click()
Dim wb1 As Workbook, wb2 As Workbook
Dim Ret1
Set wb1 = ActiveWorkbook
Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please a file to load from")
If Ret1 = False Then Exit Sub
Set wb2 = Workbooks.Open(Ret1)
If wb2.Sheet1.Name = "Sum" And wb2.Sheet2.Name = "Names" And wb2.Sheet3.Name = "Things" Then
MsgBox "Fine"
'Code Here
Else
MsgBox "Issue"
'Code Here
End If
wb2.Close SaveChanges:=False
Set wb2 = Nothing
Set wb1 = Nothing
End Sub
Unfortunately when I run the above code I get an "Object doesn't support this property or method error." on the line If wb2.Sheet1.Name = "Sum" And wb2.Sheet2.Name = "Names" And wb2.Sheet3.Name = "Things"
Help please!
You can use this function to check whether sheet exist or not:
Function IsSheetExist(wb As Workbook, shName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = wb.Worksheets(shName)
On Error GoTo 0
IsSheetExist = Not ws Is Nothing
End Function
and use it like this:
If IsSheetExist(wb2, "Sum") And IsSheetExist(wb2, "Names") And IsSheetExist(wb2, "Things") Then
MsgBox "Fine"
'Code Here
Else
MsgBox "Issue"
'Code Here
End If
if you want to check whether thouse sheets exist in workbook in specific order, you can use this approach:
Function IsContainsSheetsInOrder(wb As Workbook) As Boolean
IsContainsSheetsInOrder = False
If wb.Sheets.Count < 3 Then Exit Function
If wb.Sheets(1).Name <> "Sum" Then Exit Function
If wb.Sheets(2).Name <> "Names" Then Exit Function
If wb.Sheets(3).Name <> "Things" Then Exit Function
IsContainsSheetsInOrder = True
End Function
and then:
If IsContainsSheetsInOrder(wb2) Then
MsgBox "Fine"
'Code Here
Else
MsgBox "Issue"
'Code Here
End If
Or, sticking closer to his original script, change wb1.sheet#.Name to wb1.sheets(#).Name like this:
If wb2.Sheets(1).Name = "Sum" And wb2.Sheets(2).Name = "Names" And wb2.Sheets(3).Name = "Things" Then

How to define an object inside a for loop for excel vba

I want to import data from multiple workbooks, all from the same sheet index (3).
I'm new to vba, and I figured out how to open multiple files up, and also to copy data from one sheet to another sheet in a different workbook for a single file, but I can't seem to figure out how to do that for multiple files.
I highlighted where the error is, it tells me "object doesn't support this property or method"
Could you please help?
Thanks
Sub dataimport()
' Set Vars
Dim ArbinBook As Workbook, DataBook As Workbook
Dim i As Integer, j As Integer
Dim Caption As String
Dim ArbinFile As Variant, DataFile As Variant
' make weak assumption that active workbook is the target
Set DataBook = Application.ActiveWorkbook
' get Arbin workbook
Caption = "Please select an input file"
' To set open destination:
' ChDrive ("E")
' ChDir ("E:\Chapters\chap14")
' With Application
'Set "arbinfile" as variant, the "true" at end makes it into an array
ArbinFile = Application.GetOpenFilename(, , Caption, , True)
'Exit when canceled
If Not IsArray(ArbinFile) Then
MsgBox "No file was selected."
Exit Sub
End If
Dim targetSheet As Worksheet
Set targetSheet = DataBook.Sheets(1)
'Open for every integer i selected in the array "arbinfile"
For i = LBound(ArbinFile) To UBound(ArbinFile)
Set ArbinBook = Workbooks.Open(ArbinFile(i))
targetSheet.Range("A2", "G150").Value = ArbinBook.Sheets(3).Range("A2", "G150").Value
**ERROR at the line above**
Workbooks(DataSheet).Activate 'Reactivate the data book
Worksheets(1).Activate 'Reactivate the data sheet
ActiveWorkbook.Sheets(1).Copy _
after:=ActiveWorkbook.Sheets(1)
Workbooks(ArbinFile(1)).Activate 'Reactivate the arbin book(i)
ArbinBook.Close
Next i
Beep
End Sub
My instinct tells me that ArbinBook.Sheets(3) is a Chart-sheet, not a WorkSheet (or, at least, it is something other than a WorkSheet). It might be hidden as well, but it will still be indexed as (3).
If so, change Sheets(3) to Worksheets(3).
Added: BTW If true, this also demonstrates why using index-numbers is unreliable. If at all possible, refer to a worksheet by its name. (I appreciate that this may not always be possible.)
Added (from comments) There is nothing named DataSheet in your code. Add Option Explicit to the top of your module to indicate all such errors.
Try changing the line Set ArbinBook = Workbooks.Open(ArbinFile(i))
to Set ArbinBook = Workbooks(arbinfile(i))
I could be wrong, but I think it's trying to set your workbook object to become the action of opening another workbook, instead of labeling it as the workboook.
Sub Multiple()
Application.DisplayAlerts = False
Application.EnableEvents = False
Dim exlApp As Excel.Application
Dim exlWb1 As Excel.Workbook
Dim exlWb2 As Excel.Workbook
Dim exlWb3 As Excel.Workbook
Dim exlWs1 As Excel.Worksheet
Dim exlWs2 As Excel.Worksheet
Dim exlWs3 As Excel.Worksheet
Set exlApp = CreateObject("Excel.Application")
Set exlWb1 = exlApp.Workbooks.Open("C:\yourpath1\file1.xls")
Set exlWb2 = exlApp.Workbooks.Open("C:\yourpath2\file2.xls")
Set exlWb3 = exlApp.Workbooks.Open("C:\yourpath3\file3.xls")
Set exlWs1 = exlWb.Sheets("Sheet1")
Set exlWs2 = exlWb.Sheets("Sheet1")
Set exlWs3 = exlWb.Sheets("Sheet1")
exlWb1.Activate
exlWb2.Activate
exlWb3.Activate
'code
exlWb.Close savechanges:=True
exlWb.Close savechanges:=True
exlWb.Close savechanges:=True
Set exlWs1 = Nothing
Set exlWs2 = Nothing
Set exlWs3 = Nothing
Set exlWb1 = Nothing
Set exlWb2 = Nothing
Set exlWb3 = Nothing
exlApp.Quit
Set exlApp = Nothing
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub

accessing sheets in a different workbook from within a function in vba in Excel

I have two workbooks in Excel 2007, A and B.
Within A I have a function that needs to get certain values from workbook B. I find no way to do this within a function (within a normal sub is no problem, but I need a function - which actually is more complicated than just getting the cell(1,1) )
in A:
function getDataFromB(sheetName,row,col)
x = Application.run ("E:\B.xlsm!getData",sheetName,row,col)
getDataFromB = x
end getDataFromB
In B
function getData(sheetName,row,col)
x=sheets(sheetName).cells(row,col)
getData = x
end getData
Whenever getData within B is called it looks for sheetName in workbook A - not B. And writing
x = workbooks("E:\B.xlsm").sheets(sheetName).cells(row,col)
does not work
How would I solve this?
TIRED AND TESTED
Change
function getDataFromB(sheetName,row,col)
x = Application.run("E:\B.xlsm!getData",sheetName,row,col)
getDataFromB = x
end getDataFromB
to
Function getDataFromB(sheetName, row, col)
Dim FilePath As String, FileName As String
Dim wbTarget As Workbook
Dim x As Variant
Dim CloseIt As Boolean
'~~> Set file name and path here.
FileName = "B.xlsm"
FilePath = "E:\"
On Error Resume Next
Set wbTarget = Workbooks(FileName)
If Err.Number <> 0 Then
'~~> Open the workbook
Err.Clear
Set wbTarget = Workbooks.Open(FilePath & "\" & FileName)
CloseIt = True
End If
'~~> Check and make sure workbook was opened
If Err.Number = 1004 Then
MsgBox "File does not exist!"
Exit Function
End If
On Error GoTo 0
x = Application.Run(wbTarget.Name & "!getData", sheetName, row, col)
getDataFromB = x
If CloseIt = True Then
'~~> If the target workbook was opened by the macro, close it
wbTarget.Close savechanges:=False
Else
'~~> If the target workbook was already open, reactivate this workbook
ThisWorkbook.Activate
End If
End Function
Also in File B Change the code to
Function getData(sheetName,row,col)
x=sheets(sheetName).cells(row,col)
getData = x
End Function
You need to add "End Function" as I have done above.