command button is being renamed - vba

I am having an issue with active x control command buttons being renamed in Word 2007 without the user actually renaming them. I have directly observed the user saving the document with embedded active x controls and the names appear to be okay when they open the document, but when they save the document, they are renamed.
For example, the name property for CommandButton11 will be renamed to CommandButton111. In some cases it appears that 1 is being added to the end of the Command Button Name so 10 becomes 101, while in other cases 1 is being added to the actual value of the command button so say CommandButton10 becomes CommandButton11. The code for the command buttons does not change, but because I reference the names of the individual command buttons within the code, it obviously breaks.
The purpose of the code is to embed an OLE object in the document and place it correctly in a table.
Below is the specific code for the command button:
Private Sub CommandButton10_Click()
wrdTbl = 1
wrdRow = 11
wrdCol = 2
Set obj = CommandButton10
Call buttontransformer
End Sub
Button transformer is as follows:
Private Sub buttontransformer()
If ActiveDocument.Tables(wrdTbl).Cell(wrdRow, wrdCol).Range.Text = Chr(13) & Chr(7) Then
obj.Caption = "Remove File"
Call OLEObjectAdd
Else
ActiveDocument.Tables(wrdTbl).Cell(wrdRow, wrdCol).Select
Selection.EndKey unit:=wdRow, Extend:=wdExtend
Selection.Delete
obj.Caption = "Click to Add File"
ireply = MsgBox("Add another file?", buttons:=vbYesNo, Title:="UPLOAD NEW FILE?")
If ireply = vbYes Then
obj.Caption = "Remove File"
Call OLEObjectAdd
Else
Exit Sub
End If
End If
End Sub
And OleObjectAdd is as follows:
Private Sub OLEObjectAdd()
Dim fd As FileDialog
Dim ofd As Variant
Dim FP As String
Dim FN As String
Dim Ext As String
Dim fType As String
'Selection.MoveRight Unit:=wdCharacter, Count:=1
Set fd = Application.FileDialog(msoFileDialogFilePicker)
ActiveDocument.Tables(wrdTbl).Cell(wrdRow, wrdCol + 1).Select
With fd
.ButtonName = "Select"
.AllowMultiSelect = False
.Filters.Clear
If .Show = -1 Then
For Each ofd In .SelectedItems
FP = ofd
Debug.Print FP
FN = Right(FP, Len(FP) - InStrRev(FP, "\"))
Debug.Print FN
Ext = Right(FP, Len(FP) - InStrRev(FP, "."))
Debug.Print Ext
Next ofd
On Error GoTo 0
Else
Exit Sub
End If
End With
If Ext = "pdf" Then
fType = "adobe.exe"
ElseIf Ext = "doc" Or Ext = "docx" Or Ext = "docm" Then
fType = "word.exe"
ElseIf Ext = "xls" Or Ext = "xlsx" Or Ext = "xlsm" Then
fType = "Excel.exe"
End If
Selection.InlineShapes.AddOLEObject ClassType:=fType, _
fileName:=FP, LinkToFile:=False, _
DisplayAsIcon:=True, IconFileName:= _
fType, IconIndex:=0, IconLabel:= _
FN
Selection.Move unit:=wdCell, Count:=-2
Selection = FN
End Sub
I had done the Microsoft Fixit to address the Active-X broken controls and it works fine on several other computers I have tested this on.
I have searched high and low for an answer and cant seem to find one. Any help would be appreciated.

Related

Access VBA Form_before_update event is unnecessarily triggered

I have this code (in Form_Before_update Event) which checks for duplicate values in sdtCode field:
If DCount("[sdtCode]", "[tbl_sdt_Info]", "[sdtCode] = '" & Me.sdtCode.Value & "'") > 0 Then
Me.Undo
MsgBox "duplicates found"
End If
It works perfectly. However, after I use the following code to link the record to a picture, and when I try to move to another record the fisrst code is triggered and it gives me the "duplicates found" message!!!!
Private Sub sdtPicture_Click()
Dim fd As FileDialog
Dim i As Integer
Dim strSelectedPicture As Variant
Dim strExtension As String
Set fd = Application.FileDialog(msoFileDialogOpen)
With fd
.AllowMultiSelect = False
'show only set of extension file in dialog
.Filters.Clear
.Filters.Add "Image file", "*.jpeg;*.png;*.jpg;*.gif", 1
If .Show = -1 Then
For Each strSelectedPicture In .SelectedItems
For i = Len(strSelectedPicture) To 1 Step -1
If Mid(strSelectedPicture, i, 1) = "." Then
strExtension = Mid(strSelectedPicture, i)
Exit For
End If
Next i
Me.sdtImagePath.Value = strSelectedPicture
' if folder name doesnt exist then make new one
On Error Resume Next
MkDir "C:\dbImageArchive\students\"
' On Error GoTo 0
'if folder exist, copy image to distination folder
'file name in the drive C:\
FileCopy strSelectedPicture, "C:\dbImageArchive\students\" & "sdt_" & Me.sdtCode & strExtension
Me.sdtPicturePath.Value = "C:\dbImageArchive\students\" & "sdt_" & Me.sdtCode.Value & strExtension
'Add a text box (sdtPictureName) to display the name of the picture file
'Me.sdtPictureName = Me.sdtID & strExtension
Next strSelectedPicture
Else
'display when no file is selected
MsgBox "?? E?II ???C?", vbInformation, ""
End If
Set fd = Nothing
End With
Me.cboOrganizations.SetFocus
'Me.Refresh
End Sub
I tried the Form_after_update event. It produced further problems. Any ideas to solve this issue please. Thank you.

Is there any method to check type of file before open it with wdDialogFileOpen?

I use wdDialogFileOpen to let user open file. I want to allow user to only open .docx file. Is there any method to check type of file before open it with wdDialogFileOpen (after user choose it with wdDialogFileOpen) ?
I use following code:
With Dialogs(wdDialogFileOpen)
.Name = "."
.Show
End With
For example:
With Dialogs(wdDialogFileOpen)
.Format = "*.docx"
If .Display = True Then
If InStrRev(.Name, ".docx") > 0 Then
.Execute
End If
End If
End With
I wouldn't use the FileOpen dialog at all. Consider a FilePicker: The user selects the file and then you decide if you want to open it. Here is some code to play with.
Private Sub TestFileOpenName()
Dim Fn As String
Dim Sp() As String
' the Flt argument = 1 which results in Word documents being filtered
Fn = FileOpenName("Select a file", 1, "C:\My Dopcuments\")
' the Flt argument = "Word documents|*.doc*" which also results in
' Word documents being filtered (modify filter as required)
' Fn = FileOpenName("Select a file", "Word documents|*.doc*", "D:\My Dopcuments\")
' the Flt argument = 1 or 2 which results in Word documents being filtered
' but type drop-down allows changing to Excel.
' Specify "2||1" to make Excel the default and Word the alternative
' Fn = FileOpenName("Select a file", "1||2", "C:\My Dopcuments\")
If Len(Fn) Then
MsgBox "The selected file is" & vbCr & Fn
Sp = Split(Fn, ".")
If InStr(1, Sp(UBound(Sp)), "doc", vbTextCompare) = 1 Then
MsgBox "I will now open the document"
Else
MsgBox "Please select a Word document." & vbCr & _
"Sorry, I can't proceed."
End If
Else
MsgBox "No file was selected"
End If
End Sub
Function FileOpenName(ByVal Title As String, _
Optional ByVal Flt As Variant = 0, _
Optional ByVal Pn As String) As String
' SSY 050 ++ 14 Dec 2018
' ==================================================
' Parameters:
' Title = Form's title
' Flt = Specify filters by ID or string specs
' separated by || (= 2 x Chr(124))
' in sequence of position assignment.
' Default = no filter [=All files]
' Pn = Initial path: [=Last used]
' ==================================================
' Note: The ButtonName is "Open" by default. Another setting
' doesn't take effect until a file has been selected.
' ==================================================
Const FltDesc As Long = 0, FltExt As Long = 1
Dim Fod As FileDialog ' File Open Dialog
Dim Fts() As String ' all filters
Dim Sp() As String ' split filter
Dim i As Long
' ==================================================
Fts = Split(Flt, "||")
ReDim Sp(3)
Sp(1) = "Word documents|*.doc*"
Sp(2) = "Excel workbooks|*.xls*"
Sp(3) = "Image file|*.png, *.tif"
For i = 0 To UBound(Fts)
If IsNumeric(Fts(i)) Then Fts(i) = Sp(Fts(i))
Next i
Set Fod = Application.FileDialog(msoFileDialogFilePicker)
With Fod
.Filters.Clear
For i = 0 To UBound(Fts)
If Len(Fts(i)) Then
Sp = Split(Fts(i), "|")
.Filters.Add Sp(FltDesc), Sp(FltExt), i + 1
.FilterIndex = 1
End If
Next i
.Title = Title
.AllowMultiSelect = False
.InitialFileName = Pn
If .Show Then FileOpenName = .SelectedItems(1)
End With
End Function

Word Userform won't open in second, currently active document after opened/unloaded in first document

The headline really says it all, but here's my situation: I have a userform set up to collect user input, then uses that input in a macro and executes it. That, in itself, works exactly like I want it to. The problem comes when more than one document is open.
To illustrate: I have two documents, 'doc a' and 'doc b'. I open both documents, then select 'doc a', open the userform using a show userform macro, input my data, and hit either 'Okay' or 'Cancel' (both of which are set to unload the userform once clicked). The macro runs, and then I select 'doc b' to do the same. This time, however, when I run my 'show userform' macro, 'doc a' is selected and the userform is opened there.
This seems like a pretty basic issue, but I haven't been able to figure out any fixes. After putting 'unload me' failed to work in my button-click subs, I tried creating an unload macro and calling it from those subs instead, but neither is working for me. Any thoughts? (Also, while I'm already here- are there any good tricks to autofill the Userform with the most recently filled data? Not between opening/closing word, which I've seen some solutions for, but just while word is open, and I'm switching between active documents)
Option Explicit
Option Compare Text
Private Sub UserForm_Initialize()
Folder_Name = ""
Tag_Name = ""
Checklist.Value = True
Site_Report.Value = False
Space_Check.Value = False
End Sub
Public Sub Okay_Click()
folder = Folder_Name.Text
tag = Tag_Name.Text
tagtxt = Tag_Name.Text & "[0-9]{1,}"
tagnum = Len(Tag_Name.Text)
If Checklist.Value = True Then
report_type = "cl"
Else
report_type = "sr"
End If
If Space_Check.Value = True Then
space = "yes"
Else
space = "no"
End If
If Len(Folder_Name.Text) > 0 Then
Application.Run "Mass_Hyperlink_v_5_0"
Application.Run "UnloadIt"
Else
Application.Run "UnloadIt"
End If
Unload Me
End Sub
Private Sub Cancel_Click()
Application.Run "UnloadIt"
Unload Me
End Sub
I don't think the issue is with the macros that this userform uses (it runs fine on its own, though the code is likely a bit hackneyed), but here's the code for good measure:
Option Explicit
Option Compare Text
Public tag As String
Public tagtxt As String
Public tagnum As String
Public folder As String
Public space As String
Public report_type As String
Public Sub Mass_Hyperlink_v_5_0()
Dim fileName As String
Dim filePath As String
Dim rng As Word.Range
Dim rng2 As Word.Range
Dim fileType As String
Dim start As String
Dim temp As String
Application.ScreenUpdating = False
fileType = "jpg"
If space = "Yes" Then
start = "%20("
Else: start = "("
End If
If report_type = "cl" Then
folder = "..\Images\" & folder
Set rng = ActiveDocument.Range
Else: folder = folder
End If
If report_type = "sr" Then
folder = "Images\" & folder
Set rng = Selection.Range
Else: folder = folder
End If
Set rng2 = rng.Duplicate
'tagtxt = tag & "[0-9]{1,}"
If Len(rng) > 0 And report_type = "sr" Then
With rng.Find
.Text = tagtxt
.Forward = False
.MatchWildcards = True
.Wrap = wdFindStop
Do While .Execute(findText:=tagtxt) = True
If rng.InRange(rng2) Then
rng.Select
'Selection.start = Selection.start + Len(tag)
Selection.start = Selection.start + tagnum
'ActiveDocument.Range(Selection.start - Len(tag), Selection.start).Delete
ActiveDocument.Range(Selection.start - tagnum, Selection.start).Delete
fileName = Selection.Text
filePath = folder & "\" & Hyperlinker.Tag_Name.Text & start & fileName & ")" & "." & fileType
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, address:= _
filePath, SubAddress:="", ScreenTip:="", TextToDisplay:= _
(Hyperlinker.Tag_Name.Text & Selection.Text)
Else
Exit Sub
End If
rng.Collapse wdCollapseStart
Loop
End With
End If
If report_type = "cl" Then
With rng.Find
.Text = tagtxt
.Forward = False
.MatchWildcards = True
.Wrap = wdFindStop
Do While .Execute(findText:=tagtxt) = True
If rng.InRange(rng2) Then
rng.Select
'Selection.start = Selection.start + Len(tag)
Selection.start = Selection.start + tagnum
'ActiveDocument.Range(Selection.start - Len(tag), Selection.start).Delete
ActiveDocument.Range(Selection.start - tagnum, Selection.start).Delete
fileName = Selection.Text
filePath = folder & "\" & Hyperlinker.Tag_Name.Text & start & fileName & ")" & "." & fileType
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, address:= _
filePath, SubAddress:="", ScreenTip:="", TextToDisplay:= _
(Hyperlinker.Tag_Name.Text & Selection.Text)
Else
Exit Sub
End If
rng.Collapse wdCollapseStart
Loop
End With
End If
Application.ScreenUpdating = True
End Sub
Sub Show_Linker()
Hyperlinker.Show
Hyperlinker.Folder_Name.SetFocus
End Sub
Sub UnloadIt()
Unload Hyperlinker
End Sub
Working with UserForms in VBA can be tricky, because they're actually a kind of Class. Since VBA tries to make everything exceptionally simple, classes are not obvious, nor is how to work with them correctly. There are situations where they become traps for the unwary.
So VBA makes it possible for you to work with an instance of a UserForm class without you needing to declare and instantiate a new object, as would normally be the case with a class object. The result being that the object can "hang around" and cause unexpected behavior, such as you're seeing.
The more correct way to work with a UserForm may seem like a lot more work (code to type and complexity), but it helps to keep things sorted. Indeed, this approach would theoretically allow you to have a separate UserForm for various documents.
Dim frmHyperlinker as Hyperlinker
Set frmHyperlinker = New Hyperlinker
frmHyperlinker.Folder_Name.SetFocus
frmHyperlinker.Show
'Execution waits...
'Now you're done with it, so clean up
Unload frmHyperlinker
Set frmHyperlinker = Nothing
There's an Answer in this discussion that goes into more technical detail, although the topic of that question is different from yours: Add Public Methods to a Userform Module in VBA

VBA won't call UserForm from inside its own workbook

I have a CMD button on my sheet with the following code:
Private Sub cmdBlastoff_Click()
UserForm2.Show vbModeless 'launch gateway userform
End Sub
This code worked for a long time, but is now generating "Error 9: Subscript out of range."
The userform I am trying to call (UserForm2) is located in the same workbook.
I will put the full code of the userform below in case it's relevant, but the code in its Userform_initialize sub is:
Private Sub userform_initialize()
Sheets("hiddensheet1").Range("B5").Value = "v7.04" 'sets version # in hidden sheet
FileNameChecker_local 'runs a sub (located below in the userform module) to determine the filename and path
ValueInjector 'runs a sub (located below in the userform module) to put some values into text fields on the userform
cmdBigGo.Font.Size = 15 'sets font size of a button
End Sub
As I said earlier, this was working until recently and I am out of ideas.
So far I have tried:
1) Finding some way to explicitly point to the exact location of
userform2 by specifying the workbook in front of it:
ActiveWorkbook.UserForm2.show (doesn't work for reasons that are
now obvious) I regard a more explicit call as the most likely fix,
but don't know how to do it
2) Removing vbModeless from the call button call
3) Explicitly setting the ActiveWorkbook to the one all my stuff is
stored on, which is where the call button sits (this shouldn't be
necessary, I know)
Any other ideas?
Full code of the UserForm2 (probably not relevant, all working prior to this problem arising):
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) As Long
'should check to see if there is an output folder in the directory where COGENT sits and if not create it
'should pull default filepath to the outputs folder from the hiddensheet
'should call data baster on terminate
'DONE should allow the user to change the default save location
'DONE should allow them to change the save location THIS time.
'DONE should pull filepath from hiddensheet, check against original (?) and
'DONE Should create a default filename
Public strFileFullName As String
Public strFileJustPath As String
Public strUserFolderName As String
Public strFileName As String
Public strRawDate As String
Public strDLlink As String
Public strDLdest As String
Public strDLlocalName As String
Public strDLNameOnWeb As String
Public strOpenURLPointer As String
Dim strSaveAsErrHandler As String
Dim strQueryID As String
Private Sub userform_initialize()
Sheets("hiddensheet1").Range("B5").Value = "v7.04" 'sets version # in hidden sheet
FileNameChecker_local 'runs a sub (located below in the userform module) to determine the filename and path
ValueInjector 'runs a sub (located below in the userform module) to put some values into text fields on the userform
cmdBigGo.Font.Size = 15 'sets font size of a button
End Sub
Private Sub chkCyberDiv_Click()
If chkCyberDiv.Value = True Then
'==Cyber OUs visible==
chkNDIO.Visible = True
txtQueryID.Value = "169436"
'==Other Div OUs invisible==
chkCivilDiv.Value = False
Else
chkNDIO.Visible = False
End If
End Sub
Private Sub chkCivilDiv_Click()
If chkCivilDiv.Value = True Then
'==Civil OUs visible==
chkCivilInfoSys.Visible = True
'==Other Div OUs invisible==
chkCyberDiv.Value = False
Else
chkCivilInfoSys.Visible = False
End If
End Sub
Sub cmdBigGo_Click()
'==========Check if SaveAsNewName worked and if not kill sub==========
SaveAsNewName
If strSaveAsErrHandler = "Filename/path not viable." Then
MsgBox strSaveAsErrHandler
Exit Sub
Else
'==========Startup==========
Application.ScreenUpdating = False
Sheets("LoadingData").Visible = True
Sheets("Launchpad").Visible = False
'==========Check for/create Temp Directory==========
If FileFolderExists(strFileJustPath & "\temp") = True Then
'MsgBox "temp Folder already exists."
Else
MkDir strFileJustPath & "\temp"
'MsgBox "temp Folder didn't exist, but it do now."
End If
'==========Download Section==========
'=====Set up===== 'big gap for now = 169436
strQueryID = txtQueryID.Value
strDLlink = "https://workbench.northgrum.com/xauth/login.aspx?&ActionPageID=37&ActionParameters=QueryID%3d" & strQueryID & "%26View%3d0%26OutputToExcel%3d1"
strDLdest = strFileJustPath & "\temp\dump.xlsx"
'=====Run=====
'MsgBox "cmdBigGo thinks strDLdest = " & strDLdest
Dim done
done = URLDownloadToFile(0, strDLlink, strDLdest, 0, 0)
'==========Copy Targets from temp file==========
Sheets("LoadingData").Select
copyPathName = strFileJustPath & "\temp\"
copyFileName = "dump.xlsx"
copyTabName = "Targets"
ControlFile = ActiveWorkbook.Name
Workbooks.Open FileName:=copyPathName & "\" & copyFileName
ActiveSheet.Name = copyTabName
Sheets(copyTabName).Copy After:=Workbooks(ControlFile).Sheets(1)
Windows(copyFileName).Activate
ActiveWorkbook.Close SaveChanges:=False
Windows(ControlFile).Activate
ActiveWorkbook.Sheets("Targets").Name = "COGENT Targets"
'^source: https://msdn.microsoft.com/en-us/library/office/ff194819.aspx
'==========Delete Temp Directory==========
On Error Resume Next
Kill copyPathName & "\*.*" ' delete all files in the folder
RmDir copyPathName ' delete folder
On Error GoTo 0
'==========Create Userform1 Button on "Targets"==========
Rows("1:1").RowHeight = 26
Dim btnCOGENT As Button
Set btnCOGENT = Sheets("COGENT Targets").Buttons.Add(10.5, 4.5, 84.75, 19.5)
With btnCOGENT
.OnAction = "CallUserform1"
.Characters.Text = "COGENT"
End With
With btnCOGENT.Characters(Start:=1, Length:=6).Font
.Name = "Calibri"
.FontStyle = "Regular"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = 1
End With
Sheets("COGENT Targets").Shapes("Button 1").ScaleWidth 0.7433628319, msoFalse, _
msoScaleFromTopLeft
'==========Finish up==========
Worksheets("COGENT Targets").Activate
Sheets("LoadingData").Visible = False
Application.ScreenUpdating = True
End If
UserForm1.Show vbModeless
End Sub
Private Sub SaveAsNewName()
strSaveAsErrHandler = ""
On Error GoTo ErrorHandler
'==========Save the file with a new name==========
Dim strExpectedFileFullName As String
strExpectedFileFullName = txtFilePath.Value & "\" & txtFileName & ".xlsm"
ActiveWorkbook.SaveAs strExpectedFileFullName
FileNameChecker_local 'get the new filename
Exit Sub
ErrorHandler:
'==========Error Handler==========
If Err.Number = 1004 Then
lblSaveAsText.Caption = "That name and location didn't work... Try using 'Browse' or 'Create Outbox."
lblSaveAsText.BackColor = &H8080FF
strSaveAsErrHandler = "Filename/path not viable."
Else
MsgBox "unknown error...email Owen.Britton#NGC.com; it's probably his fault."
strSaveAsErrHandler = ""
End If
End Sub
Sub FileNameChecker_local()
'==========Check Filename and SaveAs if needed==========
strFileJustPath = ActiveWorkbook.Path
strFileFullName = ActiveWorkbook.FullName
'==========Get Filename==========
Dim i As Integer
Dim intBackSlash As Integer, intPoint As Integer
For i = Len(strFileFullName) To 1 Step -1
If Mid$(strFileFullName, i, 1) = "." Then
intPoint = i
Exit For
End If
Next i
If intPoint = 0 Then intPoint = Len(strFileFullName) + 1
For i = intPoint - 1 To 1 Step -1
If Mid$(strFileFullName, i, 1) = "\" Then
intBackSlash = i
Exit For
End If
Next i
strFileName = Mid$(strFileFullName, intBackSlash + 1, intPoint - intBackSlash - 1)
'MsgBox "strFileName = " & strFileName & vbNewLine & _
"strFileJustPath = " & strFileJustPath & vbNewLine & _
"strFileFullName = " & strFileFullName & vbNewLine & _
"ran from userform2"
End Sub
Private Sub ValueInjector()
strRawDate = Format(Date, "mm-d-yy")
'==========Inject File Name==========
If strFileName = "COGENT Launchpad" Then
txtFileName.Value = "COGENT_Pull_" & strRawDate 'might be better to include query number\
lblSaveAsText.Caption = "Give your output a descriptive name. Here's a suggestion:"
Else
'txtFileName.Value = strFileName
lblSaveAsText.Caption = "This file should be named 'COGENT Launchpad.' Some features break if you rename it."
lblSaveAsText.BackColor = &H8080FF
'MsgBox "Please rename this file 'COGENT Launchpad'"
End If
'==========Inject File Path==========
Application.ScreenUpdating = False
If IsEmpty(Worksheets("Hiddensheet1").Range("B6")) Then
cmdCreateOutbox_click
Worksheets("Hiddensheet1").Range("B6") = strFileJustPath & "\Outbox"
txtFilePath.Value = Worksheets("Hiddensheet1").Range("B6")
Else
txtFilePath.Value = Worksheets("Hiddensheet1").Range("B6")
End If
Application.ScreenUpdating = True
Worksheets("Launchpad").Activate
End Sub
Private Sub cmdBrowse_Click()
FileNameChecker_local
GetFolder (strFileJustPath)
End Sub
Private Sub cmdMakeDefault_Click()
Worksheets("Hiddensheet1").Range("B6") = txtFilePath.Value
imgCheckMark.Visible = True
End Sub
Private Sub cmdCreateOutbox_click()
'MsgBox "looking for" & strFileJustPath & "\Outbox"
If FileFolderExists(strFileJustPath & "\Outbox") Then
MsgBox "Outbox Folder already exists."
Else
MsgBox "Outbox Folder did not exist, but it does now."
MkDir strFileJustPath & "\Outbox"
txtFilePath.Value = strFileJustPath & "\Outbox"
End If
End Sub
Function GetFolder(strFilePath As String) As String
Dim fldr As FileDialog
Dim strGetFolderOutput As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strFilePath
If .Show <> -1 Then GoTo NextCode
strGetFolderOutput = .SelectedItems(1)
End With
NextCode:
GetFolder = strGetFolderOutput
txtFilePath.Value = strGetFolderOutput
Set fldr = Nothing
End Function
Private Sub userform_terminate()
Unload Me
End Sub
Somehow the hidden sheet got deleted, and it gets referred to before I check its existence and create it if missing. Thanks guys; I was barking up totally the wrong tree. Fixed and working.
Nothing was wrong with the calling of the userform at all.

Translate from VBA to VB.Net Workbook and FileDialog

I have been working on translating the code below from VBA to VB.Net. I am about 90% of the way there but I am stuck on 3 issues.
First, In VBA I used the Application.GetOpenFilename to open a file dialog from within my code, I can't seem to get that done on VB.
Second, I am trying to export a sheet and copy the data onto a sheet on my workbook. I use the following line of code:
With Globals.ThisWorkbook.Application.ActiveWorkbook.Open(strImportFile)
.Worksheets(1).Cells.Copy Workbooks(strSourceFile).Worksheets(sDestSheet).Range("A1")
.Close(savechanges:=False)
Unfortunately, the middle line is not working the Workbooks gives me an error that it cannot be used as type.
And finally, I am trying to get the Application ScreenUpdating, but that also fails. Here is the rest of my code:
Imports Microsoft.Office.Interop.Excel
Module adminModule
Function GetImportFile(Index As Long) As String
'This function is used in the import_Module to name all of the files
'that will be imported to the template. The function is primarily used by
'Sub import_OC_Data
Select Case Index
Case 1 : GetImportFile = "byemployee.csv"
Case 2 : GetImportFile = "byposition.csv"
Case 3 : GetImportFile = "statusreport.xls"
Case 4 : GetImportFile = "bydepartment.csv"
End Select
Return ""
End Function
Function GetDestSheet(Index As Long) As String
'This function is used in the import_Module to name all of the sheets
'where the files will be imported to in template.The function is primarily used by
'Sub import_OC_Data
Select Case Index
Case 1 : GetDestSheet = "byDepartment"
Case 2 : GetDestSheet = "byPosition"
Case 3 : GetDestSheet = "statusReport"
Case 4 : GetDestSheet = "byDepartment"
End Select
Return ""
End Function
Sub importRawData()
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim n As Long
Dim strSourceFile As String
Dim strImportFile As String
Dim sDestSheet As String
Dim strTitle As String = "Verify Source File"
Dim strPrompt As String = " source file does not exist." & vbNewLine & "Press OK to browse for the file or Cancel to quit"
Dim strAlert As String = ("You have not selected a workbook." & vbNewLine & "Press Retry to select a workbook or Cancel to exit program")
Dim strVmbProceedResults As String = ("Procedure Canceled. Your workbook will now close")
Dim vmbContinue As MsgBoxResult
Dim vmbProceed As MsgBoxResult
strSourceFile = Globals.ThisWorkbook.Application.ActiveWorkbook.Na
For n = 1 To 4 Step 1
strImportFile = xlWBPath & GetImportFile(n)
sDestSheet = GetDestSheet(n)
If Len(Dir(strImportFile)) > 0 Then
With Globals.ThisWorkbook.Application.ActiveWorkbook.Open(strImportFile)
.Worksheets(1).Cells.Copy Workbooks(strSourceFile).Worksheets(sDestSheet).Range("A1")
.Close(savechanges:=False)
End With
Else
vmbProceed = MsgBox(strImportFile & strPrompt, vbOKCancel + vbQuestion, strTitle)
If vmbProceed = vbCancel Then
vmbProceed = MsgBox(strVmbProceedResults, vbOKOnly + vbCritical)
Globals.ThisWorkbook.Close(saveChanges:=False)
Exit Sub
Else
strImportFile = Application.GetOpenFilename("Excel Files (*.xls;*.xlsx; *.xlsm; *.csv), *.xls; *.csv; *.xlsx; *.xlsm")
If strImportFile = "False" Then Application.ScreenUpdating = True
vmbContinue = MsgBox(strAlert, vbRetryCancel + vbCritical, "No Workbook Selected")
If vmbContinue = vbCancel Then
Globals.ThisWorkbook.Close(saveChanges:=False)
Exit Sub
Else
strImportFile = Application.GetOpenFilename("Excel Files (*.xls;*.xlsx; *.xlsm; *.csv), *.xls; *.csv; *.xlsx; *.xlsm")
Globals.ThisWorkbook.Application.ActiveWorkbook.Open(Filename:=strImportFile)
With Globals.ThisWorkbook.Application.ActiveWorkbook.Open(strImportFile)
.Worksheets(1).Cells.Copy Workbooks(strSourceFile).Worksheets(sDestSheet).Range("A1")
.Close(saveChanges:=False)
End With
End If
On Error GoTo exit_
Application.ScreenUpdating = False
Globals.ThisWorkbook.Application.ActiveWorkbook.Open(Filename:=strImportFile)
With Globals.ThisWorkbook.Application.ActiveWorkbook.Openn(strImportFile)
.Worksheets(1).Cells.Copy Workbooks(strSourceFile).Worksheets(sDestSheet).Range("A1")
.Close(savechanges:=False)
End With
exit_:
Application.ScreenUpdating = True
If Err() Then MsgBox(Err.Description, vbCritical, "Error")
End If
End If
Next n
End Sub
End Module